从一组json属性jackson创建对象

时间:2017-10-06 03:52:48

标签: java json jackson

请参考以下示例。

public class Human {
    private String name;
    private int age;
}

public class Teacher {
    private String school;
    private Human human;
}

JSON看起来像:

{
    "school": "My School",
    "age": 20,
    "name": "My Name"
}

我想从JSON字符串创建Teacher,它将Human作为内部对象,但应匹配相同级别的JSON属性。

我使用Jackson API从JSON创建java对象。

1 个答案:

答案 0 :(得分:2)

您可以将人类字段标记为@JsonUnwrapped

public class Teacher {
    private String school;
    @JsonUnwrapped
    private Human human;
    // constructor / setters
}

public class Human {
    private String name;
    private int age;
    // constructor / setters
}

public class Test {
    String str = "{ \"school\": \"My School\", \"age\": 20, \"name\": \"My Name\"  }";
    System.out.println(new ObjectMapper().readValue(str, Teacher.class));
}

这将反序列化为您正在寻找的格式。