How to determine serialization using GSON?

EDIT: Solved, will mark my answer when SO allows me :)

I use greenDAO to create a class group, and when I try to get the GSON series, it tries to serialize some of the fields generated by greenDAO (which I am not interested in) and crashes. The object to which I want to serialize links to other generated objects and lists of generated objects.

GSON says it allows the serialization described by toString () methods, I tried different approaches, but when I look at the output in a file, it just appears as the toString () method. Can someone show me how you can create a JSON object from the toString () method or suggest another way to do custom serialization.

Thank you :)

+3
source share
2 answers

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);
}
+5
source

If you're just trying to avoid serializing certain fields, remember that you can tag them with a keyword transient. This means that they will not be serialized by Gson.

+1
source

All Articles