In this tutorial we are going to see how to read JSON from file using JsonParser class available in Jackson.Jackson Streaming API is high-performance Java API for read write JSON.
JsonGenerator – is used to write JSON as String and File.
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 JSONParserExample under com.javatutorialscorner.jackson
JSONParserExample.java
package com.javatutorialscorner.jackson;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
public class JSONParserExample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JsonFactory factory = null;
JsonParser jsonParser = null;
try {
factory = new JsonFactory();
jsonParser = factory.createJsonParser(new File(
"C:\\jtc\\javatutorialscorner.json"));
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
String field = jsonParser.getCurrentName();
if ("name".equals(field)) {
jsonParser.nextToken();
System.out.println("Name : " + jsonParser.getText());
} else if ("rank".equals(field)) {
jsonParser.nextToken();
System.out.println("Rank : " + jsonParser.getIntValue());
} else if ("Tutorials".equals(field)) {
jsonParser.nextToken();
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
System.out.println("Tutorials : "
+ jsonParser.getText());
}
}
}
jsonParser.close();
} catch (JsonParseException 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
Tutorials : Java
Tutorials : Servlet
Tutorials : JSP
Tutorials : Struts 1.x
Tutorials : Struts 2.x
Tutorials : Spring
Tutorials : Hibernate
Tutorials : Log4j
Tutorials : JSON
Tutorials : Web Services
Tutorials : JSF
Tutorials : Eclipse
0 comments:
Post a Comment