Jackson supports read and write JSON via high-performance Jackson Streaming APIs, or incremental mode. Read this Jackson 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” to write JSON “field name”, “values” and “array of values” into a file name “file.json“. See code comments for self-explanatory.

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(); } } }

As result, following new file named “file.json” is created :

{
"name":"mkyong",
"age":29,
"messages":["msg 1","msg 2","msg 3"]
}
 

2. JsonParser

On the other hand, use JsonParser to parse or read above file “file.json“, and display each of the values.

Token concept
In streaming mode, every JSON “string” is consider as a single token,
and each tokens will be processed incremental, that why we call it
“incremental mode”. For example,

{
"name":"mkyong"
}
  1. Token 1 = “{“
  2. Token 2 = “name”
  3. Token 3 = “mkyong”
  4. Token 4 = “}”

See full example.

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException; public class JacksonStreamExample {
public static void main(String[] args) { try { JsonFactory jfactory = new JsonFactory(); /*** read from file ***/
JsonParser jParser = jfactory.createJsonParser(new File("c:\\user.json")); // loop until token equal to "}"
while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName();
if ("name".equals(fieldname)) { // current token is "name",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getText()); // display mkyong } if ("age".equals(fieldname)) { // current token is "age",
// move to next, which is "name"'s value
jParser.nextToken();
System.out.println(jParser.getIntValue()); // display 29 } if ("messages".equals(fieldname)) { jParser.nextToken(); // current token is "[", move next // messages is array, loop until token equal to "]"
while (jParser.nextToken() != JsonToken.END_ARRAY) { // display msg1, msg2, msg3
System.out.println(jParser.getText()); } } }
jParser.close(); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Warning
The array parsing is a bit tricky, read code comments for explanation.

Output

mkyong
29
msg 1
msg 2
msg 3
 

Conclusion

In summary, for performance critical application, use Steaming API, otherwise, just use normal Jackson data binding.

References

  1. Jackson Streaming API documentation
  2. Jackson Streaming API short example
  3. Gson Streaming example

Jackson Streaming API to read and write JSON的更多相关文章

  1. salesforce零基础学习(八十五)streaming api 简单使用(接近实时获取你需要跟踪的数据的更新消息状态)

    Streaming API参考链接: https://trailhead.salesforce.com/en/modules/api_basics/units/api_basics_streaming ...

  2. 【337】Text Mining Using Twitter Streaming API and Python

    Reference: An Introduction to Text Mining using Twitter Streaming API and Python Reference: How to R ...

  3. Update-Package : Unable to load the service index for source https://api.nuget.org/v3/index.json.

    由于更改了项目"属性"的"目标框架"(原来的框架是".NET Frameword4.5"改为了".NET Frameword4&q ...

  4. Jackson学习二之集合类对象与JSON互相转化--转载

    原文地址:http://lijingshou.iteye.com/blog/2003059 本篇主要演示如何使用Jackson对List, Map和数组与JSON互相转换. package com.j ...

  5. 解决Nuget:https://api.nuget.org/v3/index.json 访问不了的问题

    最近在家中用使用VS编译项目时,Nuget包一直下载不了,直接在浏览器中访问https://api.nuget.org/v3/index.json ,浏览器也打不开网址.把https协议改成http协 ...

  6. Visual Studio 2015 NuGet Update-Package 失败/报错:Update-Package : Unable to load the service index for source https://api.nuget.org/v3/index.json.

    起因 为了用VS2015 community中的NuGet获取Quartz,在[工具]-[NuGet包管理器]-[程序包管理器控制台]中执行 Install-Package Quartz. 却报如下错 ...

  7. Twitter REST API, Streaming API

    原文链接           用Twitter自己的话来说:   REST API The REST API provides simple interfaces for most Twitter f ...

  8. 基于Woodstox的StAX 2 (Streaming API for XML)解析XML

    StAX (Streaming API for XML)面向流的拉式解析XML,速度快.占用资源少,非常合适处理大数据量的xml文件. 详细教程和说明可以参见以下几篇文章: 使用 StAX 解析 XM ...

  9. nuget.org 无法加载源 https://api.nuget.org/v3/index.json 的服务索引

    今天添加新项目想添加几个工具包,打开NuGet就这样了  发生错误如下: [nuget.org] 无法加载源 https://api.nuget.org/v3/index.json 的服务索引. 响应 ...

随机推荐

  1. PhantomJS 一个隐形的浏览器

    下载地址: http://phantomjs.org/download.html 使用方法: 下载压缩包解压出来找到phantomjs.exe 放到python的根目录下

  2. win7 网站发布备注

    1.更改 .NET Framework 版本(改原设置v2.0 为v4.0) 2.程序池设置 3.基本设置 4.Web.config (debug="false") <sys ...

  3. 本人编写的一份前端vue面试题

    说明,此题目本人自出,做过本人所在公司的前端面试题,在此共享给大家 1. 如何在vue组件中实现v-model的功能?(只需给出关键代码) 2. 简述你知道的生命周期函数和执行时机 3. 谈谈你对计算 ...

  4. ORACLE各版本下载地址

    ORACLE 10g下载|ORACLE 10g下载地址|ORACLE 10g官网下载地址 ORACLE 10g下载地址 oracle 下载还需要用户名我自己注册了个方便大家使用下载 user:1603 ...

  5. 判断修改的中的值,用前面的,否则容易获得空值;this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue; VS bool b = (bool)this.dataGridView1.Rows[i].Cells[0].Value;

    判断修改的中的值,用前面的,否则容易获得空值:this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue;  VS     bool b = (b ...

  6. C++深度解析教程学习笔记(6)对象的构造和销毁

    1. 对象的初始化 (1)从程序设计的角度看,对象只是变量,因此: ①在栈上创建对象时,成员变量初始化为随机值 ②在堆上创建对象时,成员变量初始化为随机值 ③在静态存储区创建对象时,成员变量初始化为 ...

  7. ocx控件针对网页刷新和关闭分别进行区分处理

    当ocx加载在网页上时,如果对网页执行F5刷新事件,ocx控件会销毁ocx的窗口类,但是ocx的APP类是不会销毁的. 只有当网页被关闭时,才销毁app类. --------------------- ...

  8. Python 小练习二 数据库MySQL、Redis

    import pymysql,redis def op_mysql(host,user,password,db,sql,port=3306,charset='utf8'): conn = pymysq ...

  9. ajax 两者有什么不同

    $.ajax({            type:"POST",            url:url,            //dataType:"json" ...

  10. Java字节码

    Java字节码 javap -c 反编译.class文件可得字节码 知乎讨论https://www.zhihu.com/question/27831730 栈和局部变量操作 将常量压入栈的指令 aco ...