现在的位置: 首页 > 综合 > 正文

Jackson Streaming API To Read And Write JSON

2019年04月17日 ⁄ 综合 ⁄ 共 1498字 ⁄ 字号 评论关闭

Jackson supports>Streaming
APIs document for detail explanation on the benefit of using streaming API.

Jackson’s streaming processing is high-performance, fast and convenient, but it’s also difficult to use, because you need to handle each and every detail of JSON data.

In this tutorial, we show you how to use following Jackson streaming APIs to read and write JSON data.

  1. JsonGenerator – Write to JSON.
  2. JsonParser – Parse JSON.

1. JsonGenerator

In this example, you use “JsonGenerator”>

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;
 
public class JacksonStreamExample {
   public static void main(String[] args) {
 
     try {
 
	JsonFactory jfactory = new JsonFactory();
 
	/*** write to file ***/
	JsonGenerator jGenerator = jfactory.createJsonGenerator(new File(
			"c:\\user.json"), JsonEncoding.UTF8);
	jGenerator.writeStartObject(); // {
 
	jGenerator.writeStringField("name", "mkyong"); // "name" : "mkyong"
	jGenerator.writeNumberField("age", 29); // "age" : 29
 
	jGenerator.writeFieldName("messages"); // "messages" :
	jGenerator.writeStartArray(); // [
 
	jGenerator.writeString("msg 1"); // "msg 1"
	jGenerator.writeString("msg 2"); // "msg 2"
	jGenerator.writeString("msg 3"); // "msg 3"
 
	jGenerator.writeEndArray(); // ]
 
	jGenerator.writeEndObject(); // }
 
	jGenerator.close();
 
     } catch (JsonGenerationException e) {
 
	e.printStackTrace();
 
     } catch (JsonMappingException e) {
 
	e.printStackTrace();
 
     } catch (IOException e) {
 
	e.printStackTrace();
 
     }
 
   }
 
}

抱歉!评论已关闭.