Closed GoogleCodeExporter closed 9 years ago
Install your own type adapter! And you should avoid reporting bugs against
ancient versions of GSON.
Original comment by limpbizkit
on 10 Oct 2011 at 2:07
nevertheless this feature is often needed. I found the following code for a
type adapter wheen googling
public class XMLGregorianCalendarConverter {
public static class Serializer implements JsonSerializer {
public Serializer() {
super();
}
public JsonElement serialize(Object t, Type type,
JsonSerializationContext jsonSerializationContext) {
XMLGregorianCalendar xgcal = (XMLGregorianCalendar) t;
return new JsonPrimitive(xgcal.toXMLFormat());
}
}
public static class Deserializer implements JsonDeserializer {
public Object deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return DatatypeFactory.newInstance().newXMLGregorianCalendar(
jsonElement.getAsString());
} catch (Exception e) {
return null;
}
}
}
}
register this with
GsonBuilder gson_builder = new GsonBuilder();
gson_builder.registerTypeAdapter(XMLGregorianCalendar.class,
new XMLGregorianCalendarConverter.Serializer());
gson_builder.registerTypeAdapter(XMLGregorianCalendar.class,
new XMLGregorianCalendarConverter.Deserializer());
gson = gson_builder.create();
Original comment by mbreuer....@googlemail.com
on 22 Mar 2013 at 4:15
[deleted comment]
I had an issue with the above example. The "jsonElement.getAsString()" method
would throw an UnSupportedOperation exception and the adapter would always
returned null. I made a slight modification that worked for me. Here is what I
used to be able to DeSerialize the XMLGregorianCalendar class to json:
public class XMLGregorianCalendarConverter {
public static class Serializer implements JsonSerializer {
public Serializer() {
super();
}
@Override
public JsonElement serialize(Object t, Type type,
JsonSerializationContext jsonSerializationContext) {
XMLGregorianCalendar xgcal = (XMLGregorianCalendar) t;
return new JsonPrimitive(xgcal.toXMLFormat());
}
}
public static class Deserializer implements JsonDeserializer {
@Override
public Object deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
JsonObject obj = jsonElement.getAsJsonObject();
XMLGregorianCalendar xmlGregCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(obj.get("year").getAsInt(),
obj.get("month").getAsInt(),
obj.get("day").getAsInt(),
obj.get("hour").getAsInt(),
obj.get("minute").getAsInt(),obj.get("second").getAsInt(),
0, obj.get("timezone").getAsInt());
return xmlGregCalendar;
} catch (Exception e) {
return null;
}
}
}
}
Original comment by eric.b.f...@gmail.com
on 18 Oct 2013 at 2:59
Original issue reported on code.google.com by
swarab...@gmail.com
on 10 Oct 2011 at 8:01