Saturday, November 05, 2016

GSON

I needed to use GSON to create a JSON string to serialize an object. It is quite easy for simple objects but if your object has fields with NaN values or lists of another class type, it gets a little complicated. After I solved all these problems, the final form of GSON call was:
Gson gson = new GsonBuilder().registerTypeAdapter(MyObj.class, new MyGSONTypeAdapter()).serializeSpecialFloatingPointValues().excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT).create();
String jsonStrToSave = gson.toJson(myObj);
Details:
  • GSON does not generate data for
    • private fields without public set/get.
    • null objects
  • To include NaN in JSON string you have to call serializeSpecialFloatingPointValues().
  • To save static fields or to exclude fields, you add the transient keyword to class's field definition and call excludeFieldsWithModifiers(Modifier.TRANSIENT).
  • If your class has lists of other objects, you might get stack overflow error. One way to solve it is to define and register an adapter class. Example:
/**
* GSON type adapter class to solve stack overflow error.
* Assumes you have a class called MyClass with getVal() method.
*/
class MyGSONTypeAdapter <T extends MyClass> extends TypeAdapter {

   @Override
   public void write(JsonWriter writer, T t) throws IOException {
       if (t == null) {
           writer.nullValue();
       } else {
           writer.value(t.getVal());
       }
   }

   @Override
   public T read(JsonReader reader) throws IOException {
       double val = reader.nextDouble();
       return (T) new MyClass(val);
   }
}

No comments: