简体   繁体   中英

Genson 1.4 (JSON) not processing inherited Pojo's

I am using genson 1.4 for JSON processing in my REST implementation , JSON Inheritance is not working while using genson .please find the sample code structure below.

This is my BaseObject

This is my BaseObject

public class SynBaseObject implements Serializable
{
 private Long status;
//GettersAndSetters
}

This is my Child Class

public class PhoneNumber extends SynBaseObject
{
private  String      countryCode;
private  String      areaCode;
private  String      localNumber;
//GettersAndSetters
}

This is my Response Object

public class ResponseObject  implements Serializable
{ 
private Integer errorCode;
private String errorMessage;
private Long    primaryKey;

private SynBaseObject baseClass;

public ResponseObject()
{

}

public SynBaseObject getBaseObject()
{
return baseClass;
}

public void setBaseObject(SynBaseObject baseClass)
{
this.baseClass = baseClass;
}

public Integer getErrorCode()
{
return errorCode;
}

public void setErrorCode(Integer errorCode)
{
this.errorCode = errorCode;
}

}

This is the GENSON JSON Output:

{"baseObject":{"status":null},"errorCode":null,"errorMessage":null,"primaryKey":null}

CountryCode , areaCode and localNumber is missing in JSON,only the base class is processed .Tried the same from code like this

    Genson genson = new Genson();
    PhoneNumber number = new PhoneNumber();
    number.setCountryCode("2");
    number.setAreaCode("3");
    number.setLocalNumber("9645");
    ResponseObject responseObject = new ResponseObject();
    responseObject.setBaseObject(number);
    String serialize = genson.serialize(responseObject);
    System.out.println(serialize);

Output was the same like in the rest service.

By default Genson uses the static type during ser/de. Meaning here it will see the object as an instance of SynBaseObject and not of the concrete type PhoneNumber.

You can tell Genson to use the runtime type via configuration:

Genson genson = new GensonBuilder().useRuntimeType(true).create();

Here you can find some examples on how to customize Genson with Jaxrs .

Note that if you ever want to deserialize to a ResponseObject, then you will probably have troubles as in the json there is no information about what is the concrete type of base object. However if the consumed json is also produced by Genson you can easily solve this problem by enabling class metadata serialization builder.useClassMetadata(true) .

Some more documentation about the handling of polymorphic types in Genson.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM