Creating a nested json flat object shape with Jackson

I know that Jackson allows you to create flat json using @JsonUnwrapped to make a class object like

 public class Person { public int age; @JsonUnwrapped public Name name; public class Name { public String first, last; } } 

will be serialized to

 {"age" : 99, "first" : "Name", "last" : "Surname"} 

however, I cannot find a way to do the opposite - have a class like

 public class Person { public int age; public String firstName, lastName; } 

and its object is serialized and deserialized from

 {"age" : 99, "name" : {"first" : "Name", "last" : "Surname"}} 

Is this possible using Jackson 1.9?

+7
java json jackson
source share
1 answer

I stumbled upon this rather old question as I was looking for the same thing. I ended up with this:

 public class Person { public int age; @JsonIgnore public String firstName, lastName; protected void setName(PersonName name) { firstName = name.first; lastName = name.last; } protected PersonName getName() { return new PersonName(firstName, lastName); } protected static class PersonName { private final String first, last; @JsonCreator public PersonName(@JsonProperty("first") String first, @JsonProperty("last") String last) { this.first = first; this.last = last; } } } 
+5
source share

All Articles