How can I specify serialisation with GSON?
android, gson, java, json
Solution
Figured it out in the end :) Turns out I needed to implement a JsonSerializer for each of my objects and specify the serialisation manually. Very tedious! References to other objects require nesting, which I did by using the `toJsonTree()` method. Here's my most readable 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 a method I wrote to return a singleton Gson Object.
And it is called by:
public String infoToJson(Info i)
{
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Info.class, new InfoSerializer());
return gson.create().toJson(i);
}
Problem
EDIT: Solved, will mark my answer when SO lets me :) I'm using greenDAO to generate a bunch of classes, and it when I try to get GSON to serialise them, it seems to attempt to serialise some of the fields generated by greenDAO (Which are of no interest to me) and crashes. The object I wish to serialise references other generated objects and lists of generated objects. GSON says it allows serialisation described by toString() methods, I tried different approaches, but when I examine the output to a file it just appears as the toString() method. Could somebody show me how you could produce a JSON object from a toString() method, or suggest another way to do a custom serialisation. My Thanks :)