How to create a List from a JSON object in Java using Jackson Library

carita-feliz

Today, I would like to share an easy way to parse a JSON string into a List of Java objects in a few lines of code. Imagine the situation where you need to create a List of complex objects from a JSON array in Java, for example if we have this kind of input:

[
	{
		"title":"Title of hotspot #1",
		"x":194,
		"y":180,
		"order":0,
		"url":"http://www.alex-arriaga.com/"
	},
	{
		"title":"Title of hotspot #2",
		"x":23,
		"y":45,
		"order":1,
		"url":"http://www.alex-arriaga.com/about-me/"
	}
]

Now, suppose we have following POJO class (this class will have our fields for doing the mapping from JSON to a Java List):

package com.base22.model;

public class HotSpot{
	private String title;
	private int x;
	private int y;
	private int order;
	private String url;

	public HotSpot(){

	}

	// Create more constructors if you want :)

	public int getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("\nHotspot [ID=" + id + "]");
		sb.append("\nUrl: " + url);
		sb.append("\nDescription: " + description);
		sb.append("\nOrder: " + order);

		return sb.toString();
	}

}

One of the easiest way to reach our goal is by using Jackson library (http://jackson.codehaus.org/), which has a really good mapper. Let me show two single lines to map our JSON input into a Java List.

// This is an example of a JSON input string
String jsonString = "[{\"title\":\"Title of hotspot #1\",\"x\":194,\"y\":180,\"order\":0,\"url\":\"http://www.alex-arriaga.com/\"},{\"title\":\"Title of hotspot #2\",\"x\":23,\"y\":45,\"order\":1,\"url\":\"http://www.alex-arriaga.com/about-me/\"}]";
try{
	ObjectMapper jsonMapper = new ObjectMapper();
	List <HotSpot> hotspots = jsonMapper.readValue(jsonString, new TypeReference<List<HotSpot>>(){});
}catch(Exception e){
	e.printStackTrace();
}

Finally, you could iterate among all the objects in your new List.

for(HotSpot hotspot : hotspots){
	System.out.println(hotspot);
}

That’s it!

Be happy with your code!

 

Leave a Reply

Your email address will not be published. Required fields are marked *