In this tutorial we are going to see how to convert JSON into Map and retrieve the values
1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.jackson
3. add jackson-mapper-asl-1.9.13.jar, jackson-core-asl-1.9.13.jar into build path.
4. Create java class called JSONToMapExample under com.javatutorialscorner.jackson
JSONToMapExample.java
package com.javatutorialscorner.jackson;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
public class JSONToMapExample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ObjectMapper mapper = null;
Map<String, Object> map = null;
ArrayList<String> tutorials = null;
try {
mapper = new ObjectMapper();
map = mapper.readValue(
new File("C:\\jtc\\javatutorialscorner.json"),
new TypeReference<Map<String, Object>>() {
});
System.out.println("Name : " + map.get("name"));
System.out.println("Rank : " + map.get("rank"));
tutorials = (ArrayList<String>) map.get("tutorials");
for (String tutorial : tutorials) {
System.out.println("Tutorial : " + tutorial);
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now run the program see the following output in console.
Name : Java Tutorials Corner
Rank : 1
Tutorial : Java
Tutorial : Servlet
Tutorial : JSP
Tutorial : Struts 1.x
Tutorial : Struts 2.x
Tutorial : Spring
Tutorial : Hibernate
Tutorial : Log4j
Tutorial : JSON
Tutorial : Web Services
Tutorial : JSF
Tutorial : Eclipse
0 comments:
Post a Comment