Post Processing on Gson Deserialization

Elye
Elye
Oct 23, 2016 · 2 min read

Gson is a great library to serialize from Object to JSON and deserialize from JSON to Object. If the Object model and JSON format match identically, then everything works magically. Else we could customize the Gson object by adding Exclusion Strategy, creating registering Type Adapter to customize the serialization and deserialization etc.

But there are occasion we would really want to do something more complex, like setting a field’s value that is dependent on the other field’s value at a different hierarchy within the JSON, or some more complex condition or process to generate the result we want on some fields when deserialize from the JSON. How can we handle that?

We could think of looking into various methods the Gson provides to custom each of them. But this could cause headache. Why not just after deserialize the JSON, add another method that post-process the Object as below

var myObject = myGson.fromJson(myObjectJson, MyClass::class)
myObject.postProcess()

This looks good, but is risky that someone might forget to call myObject.postProcess() someday, and cause some weird result.

Why not Embed the post-process as part of your Gson deserialization process?

This would be pretty cool. If that is done, we then just need fromJson, and the post processing will take place at the end of deserialization.

var myObject = myGson.fromJson(myObjectJson, MyClass::class)

Here’s how this could be done.

1. Create a generic Type Adapter Factory for post processing

As shown in code below, a PostProcessingEnabler Type Adapter Factory is created, where it will generate a TypeAdapter that help perform the needed post professing after deserializing, for the class that implements the PostProcessable interface.

2. Register the PostProcessingEnabler to your Gson

The above class once setup, could be used by your Gson generically. You just need to register upon building your Gson as below.

GsonBuilder().registerTypeAdapterFactory(PostProcessingEnabler())

3. Implement the PostProcessable interface on the class

For your class that you want to have post processing, just need to implement PostProcesssable and add your needed post processing logic within the implemented gsonPostProcess() function.

class MyClass : Serializable, PostProcessable {
// All your variable data
override fun gsonPostProcess() {
// All your post processing logic you like on your object
}
}

4. You’re done! Just use it!

Now you can just do the below, it will automatically post process for you after your JSON has been deserialized.

var myObject = myGson.fromJson(myObjectJson, MyClass::class)

Elye

Written by

Elye

Learning and Sharing Android and iOS Development