Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i am trying to map certain json fields to a class instance variable.

My sample Person class looks like:

public class Person {
   private String name;
   private Address address;

   //many more fields 

   //getters and setters
}

The sample Address class is:

public class Address {
   private String street;
   private String city;
   //many more fields 

   // getters and setters
}

The json object to be deserialized to my Person class doesn't contain "address" field. It looks like:

{
"name":"Alexander",
"street":"abc 12",
"city":"London"
}

Is there a way to deserialize the json to the Person pojo where the Address fields are also mapped properly?

I have used a custom Address deserializer as mentioned in so many posts here. However, it's not being called as the Json object doesn't contain "address" field.

I had resolved this problem by mapping each field manually using JsonNode, however in my real project, it's not a nice solution.

Is there any work around for such problem using jackson? Plus if this question has been asked before then apologies on my behalf as as i have intensively searched for the solution and might have not seen it yet. .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
218 views
Welcome To Ask or Share your Answers For Others

1 Answer

@JsonUnwrapped annotation was introduced for this problem. Model:

class Person {
    private String name;

    @JsonUnwrapped
    private Address address;

    // getters, setters, toString
}
class Address {
    private String street;
    private String city;

    // getters, setters, toString
}

Usage:

ObjectMapper mapper = new ObjectMapper();
String json = "{"name":"Alexander","street":"abc 12","city":"London"}";
System.out.println(mapper.readValue(json, Person.class));

Prints:

Person{name='Alexander', address=Address{street='abc 12', city='London'}}

For more info read:

  1. Jackson Annotation Examples
  2. Annotation Type JsonUnwrapped
  3. Jackson JSON - Using @JsonUnwrapped to serialize/deserialize properties as flattening data structure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...