Jackson- Json Java Data Binding

What is JSON Java Data Binding?

A thing that most java developers love to deal with is …. Java POJO. Wouldn’t you love a black box where you can see JSON string entering from one side and POJOs coming out from the other. That’s what Jackson’s JSON java data binding does. This can be best explained by an example. We use the json from free music archive. It has an API to get latest albums in the form of JSON. we would read that json string (Click on this link to see the json) into Albums object. The Albums object contains an array of Dataset.

Here’s how The JSON Java data binding works

The first step is to create the Java class that would hold the JSON data. Look at the json. we create an Albums object to hold the entire json. The json contains an array of ‘dataset’ elements. We create a Java Object of type DataSet and in the Albums object we create a dataset property that is an array of type DataSet.

Create an instance of the com.fasterxml.jackson.databind.ObjectMapper class. This is the class that maps a JSON to a Java Object.

ObjectMapper mapper = new ObjectMapper();

We use the readValue method of the ObjectMapper to read. There are multiple versions of this method and we use the method that takes in a URL. However, there are method that read from a file, inputstream, String or a ByteArray.

The ObjectMapper caches serializers and deserializers so it would be a good idea to reuse an ObjectMapper instance for multiple conversions

If you have an InputStream then pass it to Jackson as such and do not wrap it in InputStreamReader for performance reasons.

We have disabled the feature that causes the mapper to break if it encounters an unknown property. Therefore, if the json has 10 properties and you define only two in your bean, then the other 8 will be ignored.