I found this out at the end :) It turns out I needed to implement a JsonSerializer for each of my objects and specify serialization manually. Very tiring! References to other objects require nesting, which I used using the method toJsonTree(). Here is my most widely read serializer
private class InfoSerializer implements JsonSerializer<Info>
{
@Override
public JsonElement serialize(Info src, Type typeOfSrc,
JsonSerializationContext context)
{
JsonObject obj = new JsonObject();
obj.addProperty("details", src.getDetails());
obj.addProperty("hostId", src.getHostId());
obj.addProperty("dateCreated", src.getDateCreated().toString());
obj.addProperty("expiryDate", src.getExpiryDate().toString());
obj.add("alternativeInfo", getGsonInstance().toJsonTree(src.getAlternativeInfo()));
obj.add("alternativeTimes", getGsonInstance().toJsonTree(src.getAlternativeTimes()));
return obj;
}
}
Note: getGsonInstance()is the method that I wrote to return a single Gson Object.
And it is called:
public String infoToJson(Info i)
{
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Info.class, new InfoSerializer());
return gson.create().toJson(i);
}
source
share