Safvan Kothawala Safvan Kothawala - 2 months ago 22
reST (reStructuredText) Question

Unmarshalling of Composite Objects in REST API

I am having following data structure:

class User {
String name;
ContactDetails contactDetails;
}

class ContactDetails {
String street;
String area;
}

class PersonalContactDetails extends ContactDetails {
String mobileNumber;
}

class OfficeContactDetails extends ContactDetails {
String officeNumber;
}


In above data structure, the ContactDetails field in User Object can contain Objects of type 'PersonalContactDetails' or 'OfficeContactDetails'.

The request can contain following JSON string:

{
"name" : "John",
"contactDetails" : {
"street" : "7",
"area" : "NY",
"mobileNumber" : "9898xxxxx"
}
}


The unmarshalling of above JSON string gives Object of User with contactDetails field containing only two arguments i.e. street and area.

I want the output of unmarshall to have Object of PersonalContactDetails class set in ContactDetails field with valid mobileNumber.

Answer

The request needs to show the type of the subclass:

 {
      "name" : "John",
      "contactDetails" : {
                    "@type" : "PersonalContactDetails",  
                    "street" : "7",
                    "area" : "NY",
                    "mobileNumber" : "9898xxxxx"
      }
 }

To show that extra @type property use the following annotations:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
    @JsonSubTypes.Type(PersonalContactDetails.class),

    @JsonSubTypes.Type(OfficeContactDetails.class) }
)
class ContactDetails {
      String street;
      String area;
}
Comments