Martins Irbe

voila a-z: j is for json

Continuing the Voila A-Z series, this time I will talk about JSON. We at MetaBroadcast love JSON aka (JavaScript Object Notation) because it’s a lightweight data format that is much more human-readable than some other data formats out there. In the Voila Deer world we are using Jackson to process data to and from JSON objects. Moreover, Dropwizard comes bundled with Jackson, therefore it’s a straightforward process to get up and running as Jackson aims to be the best multi-purpose Java library for working with JSON objects.

To make use of the JSON object, we have to create a data model for it. This can be simply done by creating a Java class that matches the JSON object elements. This class will be then used in the mapping process. An example class can be seen below.

It’s necessary for Jackson that we provide a default constructor method otherwise it will throw a JsonMappingException. Additionally, if there is a need for a different field name, a JsonProperty annotation can be used to specify a different name. Otherwise, the setters and getters have to follow a pattern where field names start either with get or set.

consumin’ json

Now we can use the ObjectMapper, a class used for processing Strings to POJOs. For HTTP POST methods we are specifying the input string as a method’s parameter and then we use the ObjectMapper to process the string into a POJO as can be seen below.

producin’ json

For HTTP GET methods we are mapping the processed data into the model which then is returned as part of the Response object as shown below.

processin’ without mappin’

For those who don’t want to map the input to the POJO, you can use the ObjectMapper readTree method instead. What this allows you to do is to process the JSON object directly, which then returns a JsonNode object that can be used to process the JSON object manually, for example if you need to extract a specific field.

By POSTing the following JSON object:

If we would like to return my name, we could just call the get method on the JsonNode object to get the element value:

json = fun

I love to work with JSON as I find it very reliable, easy and it can be used in many different ways as described previously. There is also a Mongo database that can store all of this beautiful magic. It’s fun to work with APIs that produce JSON objects as it takes away unnecessary complexity and makes life much easier.

If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.

blog comments powered by Disqus