0

I have a json like -

{
"type" : "employee",
"details" : {
  "name" :  "ABC",
  "age" : 12,
  "sex" : "male"
  }
}

And a Java Class like -

public class Person {
String name;
String sex;
String type;
int age;
 ----getters and setters
}

I was wondering is there a ways to directly map the attributes of the details object to the person class like details.name to Person.name. I know this can be achieved with custom deserializers, but I was hoping to avoid it. May be some annotations that GSON or Jackson provides.

Rachit Agrawal
  • 685
  • 4
  • 13
  • 35
  • I don't think you will be able to do this without a custom deserializer. This could be done by a @JsonWrapped annotation. But that is something that has been discussed but not implemented yet in jackson, no idea about GSON. – Franjavi Aug 31 '16 at 11:28

2 Answers2

0

There are a few ways to solve this, but what I would do is create the following class:

public class PersonWrapper {

   private String type;

   @JsonProperty("details")
   private Person person;

 }

EDIT:

If you don't want to add a wrapper class, you can try adding @JsonRootName(value = "details") to your Person class.

Adam
  • 2,214
  • 1
  • 15
  • 26
  • This is what I am trying to avoid. I understand this would work. But intent here to work within the given class structure – Rachit Agrawal Aug 30 '16 at 17:58
  • I just edited my answer. I have never used that annotation before but after reading the docs it seems like it will do what you want. You might also need some configuration changes. See http://stackoverflow.com/questions/11704255/jackson-json-deserialization-with-root-element – Adam Aug 30 '16 at 18:07
-1

you can use @JsonProperties for mapping

Nic.Hu
  • 1