0

我是杰克逊的初学者。如何使用 Java 创建这样的 JSON 消息?

{
    "name": "John",
    "age": "40",
    "family": {
        "parents_name": [
            "David",
            "Susan"
        ],
        "children": "yes",
        "children_names": [
            "Peter",
            "Mary"
        ]
    }
}
4

3 回答 3

1

The easiest way to do this for a beginner is to eliminate unnecessary nesting and rely on Jackson's default object binding.

You would create a class like this:

public class Person {
    private String name;
    private int age;
    private List<String> parentNames;
    private List<String> childrenNames;

    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<String> getParentNames() {
        return parentNames;
    }

    public void setParentNames(List<String> parentNames) {
        this.parentNames = parentNames;
    }

    public List<String> getChildrenNames() {
        return childrenNames;
    }

    public void setChildrenNames(List<String> childrenNames) {
        this.childrenNames = childrenNames;
    }
}

Then you can instantiate a Person from JSON like this:

Person p = ObjectMapper.readValue(jsonString, Person.class);

Note that the JSON you have in your example won't work with this object for three reasons:

  • The Person class has no Family object. I felt that adds unnecessary complexity. If you want that, create a separate Family class, and Person would contain a Family member (no pun intended).
  • I don't have a boolean for children because that can be deduced from the length of the childrenNames list.
  • The JSON will need to have childrenNames and parentNames rather than children_names and parents_name. If you want those, add @JsonProperty with the desired property names on the getters and setters for those values.
于 2013-11-06T04:37:35.660 回答
0

我从您对 Vidya 解决方案的评论中收集到,您寻求比默认绑定更多的灵活性。

Jackson 允许您创建自己的自定义序列化程序。例如:

public class Person {
    private String name;
    private int age;
    private List<String> parentsName;
    private List<String> childrenNames;

    public Person(String name, List<String> parentsName) {
        this(name, parentsName, -1, Collections.<String>emptyList());
    }

    public Person(String name, List<String> parentsName, int age) {
        this(name, parentsName, age, Collections.<String>emptyList());
    }

    public Person(String name, List<String> parentsName, int age, List<String> childrenNames) {
        this.name = name;
        this.age = age;
        this.parentsName = parentsName;
        this.childrenNames = childrenNames;
    }

    private void serialize(JsonGenerator generator, SerializerProvider arg2) throws IOException {
        generator.writeStartObject();

        generator.writeObjectField("name", name);

        if (age >= 0)
            generator.writeNumberField("age", age);

        // start family subset
        generator.writeObjectFieldStart("family");

        generator.writeArrayFieldStart("parents_name");
        for (String parent : parentsName) { 
            generator.writeObject(parent);
        }
        generator.writeEndArray();

        generator.writeObjectField("children", (childrenNames.isEmpty() ? "no" : "yes"));

        generator.writeArrayFieldStart("children_names");

        for (String child : childrenNames) {
            generator.writeObject(child);
        }
        generator.writeEndArray();

        generator.writeEndObject();
        // end family subset

        generator.writeEndObject();
    }

    public static JsonSerializer<Person> createJsonSerializer() { 
        return new JsonSerializer<Person>() {
            @Override
            public void serialize(Person me, JsonGenerator generator, SerializerProvider arg2) throws IOException, JsonProcessingException {
                me.serialize(generator, arg2);
            }            
        };
    }

    public static void main(String[] args) throws IOException {
        List<String> parentsName = Arrays.<String>asList("David", "Susan");
        List<String> childrenNames = Arrays.<String>asList("Peter", "Mary");
        Person person = new Person("John", parentsName, 40, childrenNames);

        ObjectMapper mapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule("PersonModule", new Version(1, 0, 0, null));
        simpleModule.addSerializer(Person.class, Person.createJsonSerializer());

        // pretty output for debugging
        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); 
        mapper.registerModule(simpleModule);

        System.out.println("Person json: ");
        System.out.println(mapper.writeValueAsString(person));

    }
}

这通过两种方式为您提供了更大的灵活性:

  • 您可以在序列化中应用条件逻辑

  • 您可以有多个自定义序列化程序

缺点相当明显

  • 更复杂

  • 更多的时间来实施。默认绑定几乎是免费的。这个解决方案不是。

于 2013-11-09T15:53:08.210 回答
0

在 Java 中创建一个 Person 类,具有 getName()、getAge() 等属性。然后 Jackson 可以从您的 Person 对象自动为您创建该 JSON。

于 2013-11-06T04:13:10.380 回答