1

Please refer below example.

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

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

And JSON looks like :

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

I want to create Teacher from JSON string which has Human as inner object but should match to same level of JSON properties.

I'm using Jackson API to create java object from JSON.

1 Answer 1

2

You can mark the human field as @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));
}

That will de-serialize into the format you're looking for.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! Pretty much exactly this scenario described in the docs too fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.