In this tutorial we are going to see how to write JSON into file using JsonGenerator 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 JSONGeneratorExample under com.javatutorialscorner.jackson
JSONGeneratorExample.java
package com.javatutorialscorner.jackson;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
public class JSONGeneratorExample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JsonFactory factory = null;
JsonGenerator jsonGenerator = null;
try {
factory = new JsonFactory();
jsonGenerator = factory.createJsonGenerator(new File(
"C:\\jtc\\javatutorialscorner.json"), JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Java Tutorials Corner");
jsonGenerator.writeNumberField("rank", 1);
jsonGenerator.writeFieldName("Tutorials");
jsonGenerator.writeStartArray();
jsonGenerator.writeString("Java");
jsonGenerator.writeString("Servlet");
jsonGenerator.writeString("JSP");
jsonGenerator.writeString("Struts 1.x");
jsonGenerator.writeString("Struts 2.x");
jsonGenerator.writeString("Spring");
jsonGenerator.writeString("Hibernate");
jsonGenerator.writeString("Log4j");
jsonGenerator.writeString("JSON");
jsonGenerator.writeString("Web Services");
jsonGenerator.writeString("JSF");
jsonGenerator.writeString("Eclipse");
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now run the program see the file created at specified location with following content.
{"name":"Java Tutorials Corner","rank":1,"Tutorials":["Java","Servlet","JSP","Struts 1.x","Struts 2.x","Spring","Hibernate","Log4j","JSON","Web Services","JSF","Eclipse"]}
0 comments:
Post a Comment