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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[ { "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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
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.
1 2 |
// 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/\"}]"; |
1 2 3 4 5 6 |
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.
1 2 3 |
for(HotSpot hotspot : hotspots){ System.out.println(hotspot); } |
That’s it!
Be happy with your code!