Martins Irbe

writing json consuming methods

For the past few weeks, I have been working on new features for Voila, which require programming methods that can consume a JSON object. As I hadn’t worked with JSON objects before, I found it quite daunting at first. However with some time and practice I found that it’s quite easy to do with Dropwizard as Jersey and Jackson libraries does everything for me. All I had to do was to use a specific annotation (@Consumes) indicate that the method used will consume the JSON object. Also, we need to specify media type the method will consume. In our case we wish to consume the JSON object. Therefore, we use MediaType.APPLICATION_JSON which is just a String “application/json”. It’s possible to provide the object in a parameter of a consumer, or to pass JSON object as a string which then is mapped into Java object by using ObjectMapper.

examples

To demonstrate how easy it’s to make a simple consumer method take a look at the example JSON object where I show you how to to construct the consumer method. The example contains four tags—id, type, count, titles and author. count is a type of integer while id and type are strings. The titles are lists of string objects and author is a simple Java class.

The SomeObject class would have all of these tags as fields, and we need to provide getters and setters of the tags..

An example of SomeObject would look like this: and Author class would look like this:

Here are a couple of different approaches for how to consume the previously shown JSON object.

1. Passing SomeObject as a parameter of the consumer method which would automatically convert the passed JSON object into the SomeObject instance.

2. Or by passing the JSON object as a string to the consumer method. However, this approach would require using ObjectMapper to map the input string into the instance of SomeObject.

something to keep in the mind

I have found that providing the Object to the parameter will only work if the JSON object is simple and the fields in a specific class are automatically serialized and deserialized. However, if fields are of a different type it means that we would need a custom deserializer that needs to be registered with ObjectMapper. If the object contains a field of type Timestamp, Jersey won’t know how to deal with this type of object. In a result, we would get an HTTP response code 404 when consuming the JSON Object without a custom serializer. Therefore, I find using String as the method parameter for our consumer method more straightforward as it gives straight answers when our consumer doesn’t like something.

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