Android Java <-> Json converter

With type inference

ibon
ibon
Feb 24, 2017 · 2 min read

I’ve been working a long time with multiplayer web-based/Android/iOS games, and one common operation on the server side or native clients is Json conversion to Java and vice versa.

For such repetitive tasks I created a runtime reflection-based system to aid me in the process. Serialization is straightforward. Just recursively visit every object’s fields and convert to Json with basic type inference. One important thing to detect though are cyclic dependencies. And the serializer definitely takes care of that. Inner class fields identification are avoided, and annotated fields as @Transient are also not serialized.

The deserializer, is something trickier. It basically maps and converts untyped Json data into Java types, which is not always possible, unless:

  • Java deserialization target objects have fully qualified field types. For example, it is not valid to set a type as List<TestA> because the deserialization type inference can’t instantiate such a type.
  • Java target object field types are of primitive types, List<?> subclasses, or other Java objects whose fields follow the same rules.
  • null is a first class citizen.
  • You can refer to inner classes to map objects.

For example, this is valid code for transformer deserializer:

JSONArray json = new JSONArray("[0,1,2,3]");
int[] a = JSONDeserializer.Deserialize( int[].class , json);

Or this other example, where a JSONArray is mapped to a ArrayList<TestA> objects:

public class TestE {
ArrayList<TestA> arr;
}
JSONObject json = new JSONObject(
"{" +
"arr:[" +
"{\"a\":12345,\"str\":\"1qaz\"}," +
"{\"a\":2345,\"str\":\"2wsx\"}," +
"{\"a\":34567,\"str\":\"3edc\"}," +
"null" +
"]" +
"}");
TestE a = JSONDeserializer.Deserialize( TestE.class , json);JSONObject json2 = new JSONObject( JSONSerializer.Serialize(a) );assert(json.equals(json2)); // true

You can find transformer implementation here: https://github.com/hyperandroid/transformer/

Software eater. Chocolate engineer. Human being. Writes software for food.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade