使用Jackson序列化带有嵌套对象的POJO

时间:2019-12-15 15:09:47

标签: java json serialization jackson

我想使用Jackson将这样的对象序列化为Json String。有可能吗?

public class Simple {
    public static void main(String[] args) {
        List<Person> emptylist = new ArrayList<>();
        Person p3 = new Person("grandpa", emptylist);
        Person p2 = new Person("father", emptylist);
        Person p1 = new Person("i am", emptylist);
        p2.children.add(p3);
        p1.children.add(p2);
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Getter
    @Setter
    public static class Person {
        String name;
        List<Person> children;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

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

public class TestJackson {
    public static void main(String[] args) {
        Person p3 = new Person("X", new ArrayList<Person>());
        Person p2 = new Person("Y", new ArrayList<Person>());
        Person p1 = new Person("Z", new ArrayList<Person>());
        p2.getChildren().add(p3);
        p1.getChildren().add(p2);
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.writeValue(new File("person.json"), p1);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

程序将以下内容写入person.json

{"name":"Z","children":[{"name":"Y","children":[{"name":"X","children":[]}]}]}

Person.java:

import java.util.List;

public class Person {
    private String name;
    private List<Person> children;
    public Person() {
    }
    public Person(String name, List<Person> children) {
        this.name = name;
        this.children = children;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Person> getChildren() {
        return children;
    }
    public void setChildren(List<Person> children) {
        this.children = children;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", children=" + children + "]";
    }
}