October 09, 2013, 12:00 AM — Writing a Java application (see Android) that consumes a JSON API usually involves mapping the JSON objects to Java classes for use in the software. This is a tedious and repetitive task to say the least. When something is tedious and repetitive, it’s usually a prime candidate for software automation.
When writing a Java application which relies heavily on a JSON API, it’s almost always necessary to deserialize the JSON data into native Java classes. The process goes something like this:
Download all of the JSON responses for the API, or refer to the documentation
Analyze the JSON object structure and map out your Java classes
Manually create each Java class by painstakingly typing each private property name and datatype to match the JSON properties for all objects
Create the public getter and setter messages for every property on every object
A single resulting class, in this case one from Twitter, might look something like this:
Aside from the obvious time suck involved with this process, it’s also extremely prone to errors via typos or data type mismatches.
Automatic Java stub generation
Have no fear, json gen is here. This handy website will take in a few parameters and give you back a zip file containing all of the Java object stubs generated by the JSON feed you provided it.
You can take the resulting Java classes and plug them into your application for use in deserializing/serializing your JSON feeds, complete with your package name preloaded.
This tool is a huge timesaver, however it’s not a silver bullet solution.
One significant drawback of JSON data is that the datatype of a collection or a property cannot be determined programatically with 100% accuracy. Part of this stems from the fact that it’s so lenient with how data is presented. For example, an integer value can be represented as either 1 or “1”. A tool like json gen has no way of knowing that a value of “1” should be an integer rather than a string, so you end up with a lot of string type properties. Therefore, you should go through each generated class and perform a reality check on the data types.
Another potential issue is that the tool can only be aware of the objects it finds at the time it is ran. If the API response varies, you could be missing elements in your generated files. In this twitter example, it’s possible that none of the response items has been retweeted, in which case you may be missing the Retweeted_status object completely.
Significant time savings
Even with these caveats, the json gen tool is certain to save you loads of time. You’ll have fewer errors and you’ll be able to spend more time coding the core logic for your application than you would have if you went the manual route.