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 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 to Java conversion works
ObjectMapper mapper = new ObjectMapper();
If you have an InputStream then pass it to Jackson as such and do not wrap it in InputStreamReader for performance reasons.
package com.studytrails.json.jackson;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DataBinding1 {
public static void main(String[] args) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Albums albums = mapper.readValue(new URL(url), Albums.class);
Dataset[] datasets = albums.getDataset();
for (Dataset dataset : datasets) {
System.out.println(dataset.getAlbum_title());
}
}
}
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.
package com.studytrails.json.jackson;
public class Albums {
private String title;
private Dataset[] dataset;
public void setTitle(String title) {
this.title = title;
}
public void setDataset(Dataset[] dataset) {
this.dataset = dataset;
}
public String getTitle() {
return title;
}
public Dataset[] getDataset() {
return dataset;
}
}
package com.studytrails.json.jackson;
import java.util.HashMap;
import java.util.Map;
public class Dataset {
private String album_id;
private String album_title;
private Map<String , Object> otherProperties = new HashMap<String , Object>();
public String getAlbum_id() {
return album_id;
}
public void setAlbum_id(String album_id) {
this.album_id = album_id;
}
public String getAlbum_title() {
return album_title;
}
public void setAlbum_title(String album_title) {
this.album_title = album_title;
}
public Object get(String name) {
return otherProperties.get(name);
}
}
(Note: This article’s original links is here )