1

我有一个 JSON 结构

{
  "name": "...",
  "age": "..."
}

我必须将此 JSON 映射到以下类对象

Class Response {
  Person person;
}

Class Person {
 String name;
 String age;
}

是否有任何 Jackson 注释可以帮助我在不更改 JSON 结构或修改类结构的情况下做到这一点?

4

2 回答 2

2

只需在您的课程中添加@JsonUnrapped注释即可。顺便说一下,Java 中的类是由class而不是Class定义的。你的代码不会编译失败吗?如果你还没有完成,你应该在你的类中添加 getter/setterPerson person;Response

响应类:

public class Response {
    @JsonUnwrapped
    Person person;

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}

人物类:

public class Person {
    String name;
    String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

这是一个小的测试代码来验证它:

    String json="{\n" +
            "  \"name\": \"Joe\",\n" +
            "  \"age\": \"30\"\n" +
            "}";

    ObjectMapper mapper = new ObjectMapper();
    
    // convert JSON to Response
    final Response response = mapper.readValue(json, Response.class);
    System.out.println(response.getPerson().getName());
    System.out.println(response.getPerson().getAge());

    // convert Response to JSON string
    final String s = mapper.writeValueAsString(response);
    System.out.println(s);
于 2021-10-20T09:15:13.963 回答
0

您好,这是将 json 绑定到对象 https://www.tutorialspoint.com/jackson/jackson_data_binding.htm的示例

于 2021-10-20T09:03:40.143 回答