My pojo class having some field whose datatype is XMLGregorianCalendar.
protected XMLGregorianCalendar driverBirthDate; //the value is -"1967-08-13-05:45"
While I am converting the object to json string using GSON the output is generating something else for this field.
Gson gson = new Gson();
String str = gson.toJson(pojoObj);
After convert -
"driverBirthDate": {
"day": 13,
"hour": -2147483648,
"minute": -2147483648,
"month": 8,
"second": -2147483648,
"timezone": -345,
"year": 1967
}
But I need the exact same format what pojo object holds.
Any quick help will be great.
The reason why Gson outputs the XMLGregorianCalendar as JSON object is because it does not have a built-in adapter for this type and therefore falls back to the reflection based adapter which emits the values of all fields of the class.
You can solve this by creating a custom
TypeAdapter:(
DatatypeFactoryisjavax.xml.datatype.DatatypeFactory)And then create the
Gsoninstance using aGsonBuilderon which you register that adapter:Using
registerTypeHierarchyAdapterhere is necessary becauseXMLGregorianCalendaris an abstract class and your type adapter is supposed to handle the subclasses as well.