Wednesday, July 6, 2011

JSON Hiccups

This is my first entry into the JSON world and everything looked pretty straight-forward from the outset.
When the time came to dig in and use JSON and map it back to POJO's, issues started sprouting, but nothing too daunting or complicated.

Issue 1: I had to call a RESTful webservice which responds with application/json type. I dont have the JSON schema available and the JSON object is quite large (requiring quite a few classes and fields). Now I needed to generate the java classes, but couldnt figure out an easy way (like how you would generate classes using XML schema). I could lookup the json string and then create the Java classes manually, which is what I did for the simpler json responses..but for the larger responses, it didnt seem to be a smart way to go about. After some googling, found this wonderful link http://jsongen.byingtondesign.com/ which generates the java files for you if you could provide the url for the json request! What a time-saver?

Issue 2:  This time, I was getting a json string which didnt follow the standard syntax. All the property names were capitalized and some properties were just named '$'. While reading about the json mapping, I understood that badgerfish, when creating json string from xml schema generates '$' as the property name to represent the text between the xml element. ex:
XML: <customer>Arnold</customer> is represented as
JSON: {"$": "Arnold"}
But due to the capitalized property names, when I tried to use ObjectMapper.readValue(json, Class)...it fails due to the fact that its looking for a property with lowercase name. To overcome that, I then had to use @JsonProperty annotation on each property in java file to match the property name in json and everything went smooth after that.  

Issue 3: Some of the generated java files didnt include all the property names that were found in the json string. So when I tried to map the values from json into java objects, it failed with an org.codehaus.jackson.map.exc.UnrecognizedPropertyException. If you need that property, you'd have to add that in your generated java file. But assuming you dont need that property and you dont want to keep adding those fields which is not needed by your app, the simplest way is to disable the FAIL_ON_UNKNOWN_PROPERTIES feature in Jackson's deserialization config by calling:

ObjectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

No comments: