Search code examples
javajsonjacksonjackson-databindjackson-annotations

How to map unwrapped JSON field to wrapped object with Jackson?


I have a JSON of structure

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

I have to map this JSON to following class object

Class Response {
  Person person;
}

Class Person {
 String name;
 String age;
}

Is there any Jackson annotation that helps me do this without changing the JSON structure or modifying the class structure?


Solution

  • Just add @JsonUnrapped annotation over Person person; in your Response class. And by the way, classes in Java are defined by class not Class. Doesn't your code fails to compile? And you should add getters/setters to your classes if you haven't done already

    Response class:

    public class Response {
        @JsonUnwrapped
        Person person;
    
        public Person getPerson() {
            return person;
        }
    
        public void setPerson(Person person) {
            this.person = person;
        }
    }
    

    Person class:

    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;
        }
    }
    

    And here is a small test code to verify it:

        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);