Jackson 공부 해 요.

Jackson 은 자바 대상 을 JSON 문자열 로 정렬 할 수 있 고 JSON 문자열 을 자바 대상 으로 역 정렬 할 수 있 는 프레임 워 크 입 니 다. 
본문의 모든 내용 은 Java JSON Jackson Introduction 찾 을 수 있 습 니 다. 여 기 는 자신 이 나중에 참고 할 수 있 도록 기록 되 어 있 습 니 다. 만약 시간 이 충분 하 다 면 원문 을 읽 는 것 을 권장 합 니 다.
이것 은 사용자 정의 (반) 서열 화 를 소개 하 는 또 다른 글 이다. http://www.baeldung.com/jackson-custom-serialization
서열 화 든 반 서열 화 든 잭 슨 은 세 가지 방식 을 제공 했다.
1. JSON Java Object 
2. JSON JSONNode Tree (XML 과 유사 한 DOM 트 리)
3. JSON JSon Stream (이것 은 낮은 차원 의 api 로 강하 지만 번거롭다)
Jackson 은 많은 유용 한 주 해 를 제공 하여 서열 화 를 맞 추 었 지만, 우 리 는 그것 의 주 해 를 전혀 사용 하지 않 아 도 절대 다수의 작업 을 완성 할 수 있다.다음은 위의 세 가지 방식 으로 하나씩 소개 하 겠 습 니 다.
 
JSON Java Object 
다음 Person 클래스 는 일반적인 자바 POJO 입 니 다.기본 형식 (String, Date 포함) 과 집합 형식, 사용자 정의 Address 형식 을 포함 합 니 다.
메모: 기본적으로 Jackson 은 모든 Public 속성 과 getter 방법 을 가 진 속성 을 처리 합 니 다 (역 직렬 화 는 setter 가 필요 합 니 다)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Person {
    private String name;
    private int age;
    public Date birth;
    private Address address;
    private List friends = new ArrayList<>();
    public Map info = new HashMap<>();
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public List getFriends() {
        return friends;
    }
    public void setFriends(List friends) {
        this.friends = friends;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    
    //         ,          ,     @JsonCreator      
    public Person(){}
    
    public Person(String name, int age, Address address, Date birth, String... friends){
        this.name = name;
        this.age = age;
        this.address = address;
        this.birth = birth;
        this.friends.addAll(Arrays.asList(friends));
    }
    
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("name: " + this.name + "
"); sb.append("age: " + this.age + "
"); sb.append("address: " + this.address + "
"); sb.append("birth: " + this.birth + "
"); this.friends.forEach(x -> sb.append("friend:"+ x + "
")); return sb.toString(); } }

 
public class Address {
    public String homeAddress;
    public String workAddress;
    
    // Person  ,                 
    public Address(){}
    
    public Address(String homeAddress, String workAddress) {
        this.homeAddress = homeAddress;
        this.workAddress = workAddress;
    }

    @Override
    public String toString() {
        return "home:" + this.homeAddress + "  " + "work:" + this.workAddress;
    }
}

 
다음은 잭 슨 을 사용 하여 이 Person 대상 을 서열 화 합 니 다.
직렬 화:
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class SerializeTest {
    public static void main(String[] args) throws ParseException, JsonGenerationException, JsonMappingException, IOException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date birth = format.parse("2010-10-10");
        
        Address address = new Address("New York", "Tokyo");
        Person person = new Person("zhangsan", 11, address, birth, "weiying", "caifang");
        person.info.put("height", "175cm");
        person.info.put("weight", "80kg");
        
        //  ObjectMapper         
        ObjectMapper mapper = new ObjectMapper();
        
        //          
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        //    DateFormat,ObjectMapper   Date          
        mapper.setDateFormat(format);
        //  map key             
        mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        
        //
        mapper.writeValue(new File("person.json"), person);
    }
}

 
역 직렬 화:
import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DeserializeTest {
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        //       ObjectMapper  
        ObjectMapper mapper = new ObjectMapper();
        
        //            json                 
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //   configure(xxx,false)    disable(xxx),               。
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        
        //
        Person person = mapper.readValue(new File("person.json"), Person.class);
        
        System.out.println(person);
    }
}

 위의 예 에서 우 리 는 Jackson 의 가장 기본 적 인 (반) 직렬 화 과정 을 보 았 다. 다음은 맞 춤 형 (반) 직렬 화 에 사용 되 는 주 해 를 소개 한다.
1. @ JSonProperty - 기본 적 인 상황 에서 Jackson 은 모든 Public 의 속성 과 getter (직렬 화) 와 setter (반 직렬 화) 의 속성 을 처리 합 니 다.하지만 우 리 는 사용 할 수 있다. @제 이 슨 프로 퍼티 는 잭 슨 이 처리 하고 자 하 는 속성 을 수 동 으로 지정 합 니 다.이 동시에 자바 대상 이 json 에 비 친 속성 이름 을 변경 할 수 있 습 니 다 (기본 값 은 같 습 니 다). @제 이 슨 프로 퍼티 는 JAXB 의 @ XmlElement 주해 에 해당 한다.
import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 *   Dog      public    getter  ,      @JsonProperty        ( )      ,         json      
 */
public class Dog {
    @JsonProperty("dog_name")
    private String name = "dahuang";
    private int age;
    
    @JsonProperty("dog_age")
    private int tellYourAge(){
        return this.age;
    }
    
    @JsonProperty("dog_age")
    private void giveMeAge(int age){
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "dog(name: " + name + ";age: " + age + ")";
    }
    
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        //Jackson           
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        //  ObjectMapper     ,      ,          。
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //       
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        //               
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        
        mapper.writeValue(new File("dog.json"), new Dog());
    
        Dog dog = mapper.readValue(new File("dog.json"), Dog.class);
        System.out.println(dog);
    }
}

 
2. @ JSonCreator - 위의 Person 의 예 에서 우 리 는 매개 변수 가 있 는 구조 기 를 정의 하 는 것 외 에 인삼 이 없 는 기본 구조 기 를 정의 해 야 합 니 다. 이것 은 반 직렬 화 과정 에서 Jackson 이 매개 변수 가 있 는 구조 기 에 어떤 파 라 메 터 를 전달 해 야 할 지 모 르 기 때 문 입 니 다.우 리 는 구조 기 에서 @ JSonCreator 를 사용 하고 매개 변수 목록 에서 @ JSonProperty 를 사용 할 수 있 습 니 다. 이렇게 하면 역 직렬 화 될 때 Jackson 은 이 구조 기 를 어떻게 사용 해 야 하 는 지 알 게 될 것 입 니 다. 이 럴 때 우 리 는 그 인삼 이 없 는 기본 구조 기 를 정의 할 필요 가 없습니다.
@ JSonCreator 는 반 직렬 화 과정 에서 만 유용 합 니 다.
import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Dog {
    public String name;
    public int age;
    
    @Override
    public String toString() {
        return this.name + ":" + this.age;
    }
    //         ,Jackson  json   name     dog_name  ,  json   age     dog_age  。
    @JsonCreator
    public Dog(@JsonProperty("name") String dog_name, @JsonProperty("age") int dog_age){
        this.name = dog_name;
        this.age = dog_age;
    }
    
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(new File("dog.json"), new Dog("dahuang", 11));
        
        Dog dog = mapper.readValue(new File("dog.json"), Dog.class);
        System.out.println(dog);
    }
}

 
3. @ JsonAnyGetter and @ JsonAnySetter - 이러한 장면 을 구상 합 니 다. 자바 대상 에서 명확 하 게 지정 한 속성 (@ JsonProperty 로 지정 한 것 포함) 을 제외 하고 우 리 는 무 작위 로 다른 속성 을 추가 하여 무 작위 속성 도 json 에 투사 할 수 있 기 를 바 랍 니 다.이 럴 때 우 리 는 이러한 불확실 한 속성 을 하나의 map 에 넣 고 @ JSonAnyGetter 와 @ JSonAnySetter 를 사용 하여 이 map 를 처리 하 는 방법 을 수식 한 다음 에 Jackson 은 이러한 불확실 한 속성 을 처리 할 수 있 습 니 다.이 두 속성 은 JAXB 의 @ XmlAnyElement 와 @ XMLanyAttribute 에 해당 합 니 다.
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Dog {
    private Map any = new HashMap<>();
    
    @JsonAnyGetter
    public Map getAny(){
        return this.any;
    }
    
    @JsonAnySetter
    public void setAny(String key, String value){
        this.any.put(key, value);
    }

    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        Dog dog = new Dog();
        //suck a big dog!!!
        dog.setAny("height", "175cm");
        dog.setAny("weight", "80kg");
        
        ObjectMapper mapper = new ObjectMapper();
        
        mapper.writerWithDefaultPrettyPrinter().writeValue(new File("dog.json"), dog);
        
        Dog dog2 = mapper.readValue(new File("dog.json"), Dog.class);
        dog2.getAny().forEach((x, y) -> System.out.println(x + "-->" + y));
    }
}

 
4. @ JsonIgnore Properties and @ JsonIgnore - 자바 대상 의 Public 속성 이나 getter 방법의 속성 을 Jackson 이 처리 하 는 것 을 원 하지 않 는 다 면 이 두 속성 을 사용 하여 무시 할 수 있 습 니 다. JAXB 에서 @ XmlTransient 에 해당 합 니 다.
import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@JsonIgnoreProperties({"name", "age"})
public class Dog {
    public String name = "dahuang";
    public int age = 11;
    @JsonIgnore
    public String home = "CHN";

    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        //Dog            ,             json 
        mapper.writeValue(System.out, new Dog());
    }

}

 
@ JSonIgnoreProperties and @ JSonIgnore 를 사용 하여 특정 속성 을 무시 하 는 것 외 에 아래 와 같이 빈 속성 을 무시 할 수 있 습 니 다.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class Dog {
    public String name = "";
    public List info = new ArrayList<>();
    public List info2 = null;
    
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        
        //           null      ,  Dog           JSON 
        mapper.setSerializationInclusion(Include.NON_EMPTY);
        mapper.writeValue(System.out, new Dog());
    }
}

 
5. 직렬 화 과정 에서 유형 정보 저장
다음은 부모 클래스 Animal 과 그 두 개의 하위 클래스 Dog 와 Cat, Person 클래스 는 Animal 형식의 속성 을 정의 합 니 다.
Animal:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Animal {
    public String name;
    public int age;

    @JsonCreator
    public Animal(@JsonProperty("name") String name, @JsonProperty("age") int age){
        this.name = name;
        this.age = age;
    }
}

 
Dog:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Dog extends Animal{
    public String size;
    
    @JsonCreator
    public Dog(@JsonProperty("name") String name, @JsonProperty("age") int age, @JsonProperty("size") String size){
        super(name, age);
        this.size = size;
    }
}

 
Cat:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Cat extends Animal{
    public String color;
    
    @JsonCreator
    public Cat(@JsonProperty("name") String name, @JsonProperty("age") int age, @JsonProperty("color") String color){
        super(name, age);
        this.color = color;
    }
}

 
Person:
public class Person {
    public Animal animal;
}

 
우 리 는 현재 Person 의 animal 속성 을 Dog 대상 으로 설정 한 다음 Person 대상 을 직렬 화 한 다음 에 얻 은 json 문자열 을 반 직렬 화 합 니 다.
import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        Person person = new Person();
        person.animal = new Dog("dahuang", 11, "big");
        
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        
        mapper.writeValue(new File("person.json"), person);
        
        Person p2 = mapper.readValue(new File("person.json"), Person.class);
        //          Person  animal        Dog  ,          animal       animal  。
        //   ,  Animal         ,       。
        System.out.println(p2.animal.getClass().getName());
    }
}

 
위의 예 에서 직렬 화 된 결 과 는:
{
  "animal" : {
    "name" : "dahuang",
    "age" : 11,
    "size" : "big"
  }
}

 
위의 결과 에서 우 리 는 Jackson 이 animal 속성의 구체 적 인 유형 정 보 를 저장 하지 않 은 것 을 보 았 다. 이렇게 반 서열 화 할 때 Jackson 은 이전에 서열 화 되 었 을 때의 진정한 유형 을 알 수 없다. 이것 이 바로 위 에서 반 서열 화 된 후에 얻 은 것 이 Dog 가 아 닌 Animal 인 이유 이다.
우 리 는 Animal 을 다음 과 같이 수정 합 니 다.
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class")
@JsonSubTypes({ @Type(value = Dog.class, name = "lion"), @Type(value = Cat.class, name = "elephant") })
public class Animal {
    public String name;
    public int age;

    @JsonCreator
    public Animal(@JsonProperty("name") String name, @JsonProperty("age") int age){
        this.name = name;
        this.age = age;
    }
}

 
그 다음 에 위의 직렬 화 와 반 직렬 화 된 코드 를 다시 실행 하면 Person 의 animal 속성 이 Dog 대상 임 을 얻 을 수 있 습 니 다.직렬 화 된 json 은:
{
  "animal" : {
    "@class" : "com.massclouds.info.Dog",
    "name" : "dahuang",
    "age" : 11,
    "size" : "big"
  }
}

 우 리 는 위의 json 결과 에 @ class 의 속성 이 하나 더 있 는 것 을 보 았 습 니 다. 이것 은 animal 속성의 유형 정 보 를 대표 합 니 다.
 Animal 의 list 나 Animal 을 value 로 하 는 map 를 직접 정렬 할 때 위의 설정 은 json 문자열 에 형식 정 보 를 저장 할 수 없습니다. Animal 을 포함 하 는 list 와 map 를 직접 정렬 하 는 방법 을 보 여 줍 니 다.
직렬 화:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class SerializeList {
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        List animal_list = new ArrayList<>();
        animal_list.add(new Dog("dahuang", 11, "big"));
        animal_list.add(new Cat("miaomiao", 11, "grey"));
        
        Map animal_map = new HashMap<>();
        animal_map.put("dog", new Dog("dahuagn", 11, "big"));
        animal_map.put("cat", new Cat("miaomiao", 11, "white"));
        
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        
        mapper.writerFor(new TypeReference>(){}).writeValue(new File("list.json"), animal_list);
        
        mapper.writerFor(new TypeReference>(){}).writeValue(new File("map.json"), animal_map);
    }
}

 
역 직렬 화:
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SerializeList {
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        
        List animal_list = mapper.readValue(new File("list.json"), new TypeReference>(){});
        animal_list.forEach(animal -> System.out.println(animal.getClass().getName()));
        
        Map animal_map = mapper.readValue(new File("map.json"), new TypeReference>(){});
        animal_map.forEach((key, value) -> System.out.println(key + " --> " + value.getClass().getName()));
    }
}

 
위 에서 주의해 야 할 점 은 Class 대상 에서 일반적인 정 보 를 휴대 할 수 없 기 때문에 TypeReference 를 사용 해 야 한 다 는 것 이다.
 
6. Mix-in 
우리 가 제3자 라 이브 러 리 의 자바 형식 을 사용 할 때, 우 리 는 형식 에 주 해 를 직접 사용 할 수 없습니다. 이때 우 리 는 Jackson 이 제공 하 는 Mix - in 기능 을 사용 할 수 있 습 니 다.
우 리 는 다음 과 같은 Dog 클래스 가 있 습 니 다.
public class Dog {
    public String name;
    private int age;
    
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    public Dog(String name, int age){
        this.name = name;
        this.age = age;
    }
}

 
우 리 는 추상 류 를 정의 해 야 한다. 만약 에 우리 가 Dog 류 의 어느 곳 에서 주 해 를 사용 하고 싶다 면 우 리 는 이 추상 류 에서 똑 같은 성명 (속성 이나 방법) 을 정의 한 다음 에 주 해 를 사용 해 야 한다. 예 를 들 어 우 리 는 Dog 중의 getAge 방법 에서 @ JSonProperty 주 해 를 사용 하고 싶다 면 우 리 는 이 추상 류 에서 getAge 라 는 추상 적 인 방법 을 정의 한다.그리고 이 추상 적 인 방법 에 @ JSonProperty 를 사용 합 니 다.다음은 이 추상 류 의 실현 이다.
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public abstract class DogMixin{
    @JsonProperty("dog_name")
    public String name;
    
    @JsonProperty("dog_age")
    public abstract int getAge();
    
    @JsonProperty("dog_age")
    public abstract void setAge(int age);
    
    @JsonCreator
    public DogMixin(@JsonProperty("dog_name") String name,@JsonProperty("dog_age") int age){
        //        。。。
    }
}

 
그리고 직렬 화 할 때 아래 처럼 사용 하면 Dog 류 에서 직접 주 해 를 사용 하 는 것 과 같은 효 과 를 낼 수 있 습 니 다.
import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        //       Mixin   
        mapper.addMixIn(Dog.class, DogMixin.class);
        
        Dog dog = new Dog("dahuang", 11);
        mapper.writerWithDefaultPrettyPrinter().writeValue(new File("dog.json"), dog);
        
        Dog dog2 = mapper.readValue(new File("dog.json"), Dog.class);
        System.out.println(dog2.getAge() + " : " + dog2.name);
    }
}

 
JSON JsonNode Tree
XML 의 DOM 트 리 와 같이 우 리 는 json 노드 트 리 를 통 해 json 을 구축 할 수 있 습 니 다. 물론 json 문자열 을 노드 트 리 로 역 정렬 할 수도 있 습 니 다.
Tree2JSON
import java.io.FileOutputStream;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Tree2JSON {
    public static void main(String[] args) throws IOException {
        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator generator = jsonFactory.createGenerator(new FileOutputStream("tree.json"));
        
        ObjectMapper mapper = new ObjectMapper();
        
        JsonNodeFactory factory = new JsonNodeFactory(false);
        //       
        ObjectNode person = factory.objectNode();
        //          
        person.put("name", "zhangsan");
        person.put("age",  11);
        
        //
        ObjectNode address = factory.objectNode();
        address.put("homeAddress", "New York");
        address.put("workAddress", "Tokyo");
        person.set("address", address);

        //        Array  ,      Array            
        ArrayNode friends = factory.arrayNode();

        ObjectNode friend1 = factory.objectNode();
        friend1.put("name", "weiying");
        
        ObjectNode friend2 = factory.objectNode();
        friend2.put("name", "caifang");
        
        friends.add(friend1).add(friend2);
        person.set("friends", friends);
        
        mapper.writeTree(generator, person);
    }
}

 
제 이 슨 문자열 은 다음 과 같 습 니 다.
{"name":"zhangsan","age":11,"address":{"homeAddress":"New York","workAddress":"Tokyo"},"friends":[{"name":"weiying"},{"name":"caifang"}]}

 
다음은 이 JSON 문자열 을 트 리 로 거꾸로 정렬 하고 이 트 리 를 옮 겨 다 닙 니 다.
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;

public class JSON2Tree {
    public static void main(String[] args) throws JsonProcessingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        // ObjectMapper  json,     
        JsonNode root = mapper.readTree(new File("tree.json"));

        review(root);
    }

    //        
    private static void review(JsonNode root) {
        if (root.getNodeType().equals(JsonNodeType.OBJECT)) {
            Iterator fieldNames = root.fieldNames();
            while (fieldNames.hasNext()) {
                String fieldName = fieldNames.next();
                JsonNode node = root.get(fieldName);
                System.out.println(fieldName);
                review(node);
            }
        } else if (root.getNodeType().equals(JsonNodeType.ARRAY)) {
            ArrayNode array = (ArrayNode) root;
            Iterator iter = array.iterator();
            iter.forEachRemaining(x -> review(x));
        } else {
            System.out.println(root);
        }
    }
}

 
JSON Json Stream 
Jackson 은 제 이 슨 의 api 를 낮은 차원 으로 작 동 합 니 다. 쉽게 말 하면 Jackson 은 제 이 슨 문자열 을 읽 은 후에 제 이 슨 의 모든 로 고 를 차례대로 해당 하 는 token 을 만 듭 니 다. 예 를 들 어 '{' 는 대상 의 시작 을 나타 내 면 Jackson 은 대상 이 시작 하 는 token 을 만 듭 니 다. 강력 하지만 번 거 로 워 서 사용 하 는 것 을 추천 하지 않 습 니 다.
import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

public class StramParser {
    public static void main(String[] args) throws JsonParseException, IOException {
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(new File("person.json"));
        
        while(!parser.isClosed()){
            //          token     (     )
            JsonToken token = parser.nextToken();
            System.out.println(token);
            System.out.println(parser.getText());
        }
    }
}

 
import java.io.IOException;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;

public class StreamGenerator {
    public static void main(String[] args) throws IOException {
        JsonFactory factory = new JsonFactory();
        JsonGenerator generator = factory.createGenerator(System.out);
 
        // start writing with {
        generator.writeStartObject();
        generator.writeFieldName("name");
        generator.writeString("zhangsan");
        generator.writeFieldName("address");
        // start an array
        generator.writeStartArray();
        generator.writeStartObject();
        generator.writeStringField("homeAddress", "New York");
        generator.writeEndObject();
        generator.writeStartObject();
        generator.writeStringField("workAddress", "Tokyo");
        generator.writeEndObject();

        generator.writeEndArray();
        generator.writeEndObject();
 
        generator.close();
    }
}

 
다음으로 전송:https://www.cnblogs.com/zh1164/p/6808177.html

좋은 웹페이지 즐겨찾기