1

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?

2 Answers2

2

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);
pleft
  • 7,567
  • 2
  • 21
  • 45
  • Thanks for sharing, are you sure JSONUnwrapped always works for Deserialization ? The documentation doesnt mention it https://fasterxml.github.io/jackson-annotations/javadoc/2.8/com/fasterxml/jackson/annotation/JsonUnwrapped.html – Ajay Sabarish Oct 20 '21 at 09:51
  • @AjaySabarish In my test code I show both serialization/deserialization (json->Response and Response->json), you can check on your own if it works as expected. – pleft Oct 20 '21 at 11:21
0

Hello this a example to bind the json into the object https://www.tutorialspoint.com/jackson/jackson_data_binding.htm

KimKulling
  • 2,654
  • 1
  • 15
  • 26
  • Thanks for sharing it, but in the example cited, JSON and Class structures are similar but how to map if the JSON is unwrapped ? Can you please apply it to my example ? – Ajay Sabarish Oct 20 '21 at 09:06