We can introduce Groovy into our Java projects at grassroots level. In this post we see how we can use the JsonSlurper
class in our Java code to read JSON data. Once we have included the Groovy libraries in our project, for example by adding a dependency in a Maven POM file, we can use Groovy classes in our Java applications. And once we have Groovy in our project we might extend the use of Groovy further...
The JsonSlurper
class has a parseText()
and parse()
method to read in JSON data. We get back a Map
with values from the JSON structure. Let's see how we can use it in a simple Java application:
package com.mrhaki.sample; import groovy.json.JsonSlurper; import java.util.List; import java.util.Map; public class JsonParser { public static void main(String[] args) { String jsonText = "{\"user\":{\"name\":\"mrhaki\",\"age\":38,\"interests\":[\"Groovy\",\"Grails\"]}}"; JsonSlurper jsonSlurper = new JsonSlurper(); Object result = jsonSlurper.parseText(jsonText); Map jsonResult = (Map) result; Map user = (Map) jsonResult.get("user"); String name = (String) user.get("name"); Integer age = (Integer) user.get("age"); List interests = (List) user.get("interests"); assert name.equals("mrhaki"); assert age == 38; assert interests.size() == 2; assert interests.get(0).equals("Groovy"); assert interests.get(1).equals("Grails"); } }
Or use a URL with JSON content:
package com.mrhaki.sample; import groovy.json.JsonSlurper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; public class JsonUrlParser { private static final String JSON_URL = "http://www.mrhaki.com/samples/sample.json"; public static void main(String[] args) throws IOException, MalformedURLException { URL url = new URL(JSON_URL); InputStream urlStream = null; try { urlStream = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream)); JsonSlurper jsonSlurper = new JsonSlurper(); Object result = jsonSlurper.parse(reader); Map jsonResult = (Map) result; Map user = (Map) jsonResult.get("user"); String name = (String) user.get("name"); Integer age = (Integer) user.get("age"); List interests = (List) user.get("interests"); assert name.equals("mrhaki"); assert age == 38; assert interests.size() == 2; assert interests.get(0).equals("Groovy"); assert interests.get(1).equals("Grails"); } finally { if (urlStream != null) { urlStream.close(); } } } }
Once we have the Groovy libraries in our classpath we can run the Java application with $ java -ea com.mrhaki.sample.JsonParser
and the assertions should be okay.