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. IE9以上版本无法更換会员头像

    解决方法一:把网址加入"信任的網站" 就可以了 解决方法二:打开IE8的窗口-工具-- Intelnet选项-- 安全-- 自定义级别把“将文件上传到服务器时包含本地目录路径”这一 ...

  2. 【转】Jmeter + DadBoby 安装使用

    一直接触LR比较多,这阵子突然想了解一下开源的性能测试工具,无意中接触到了Jmeter+Badboy,这两款工具对于想进行性能测试,但又对LR高额的商业费用望而止步的小公司可谓是再适合不过了. 自已小 ...

  3. innodb事务日志详解

    首先看InnoDB的缓存和文件的关系图如下: InnoDB事务日志功能介绍 InnoDB使用日志来减少提交事务时的开销.因为日志中已经记录了事务,就无须在每个事务提交时把缓冲池的脏块刷新(flush) ...

  4. casperjs 安装试用

    纠结了好久,一直报错, 具体错误信息现在已经忘了,后来看了官网的prerequisite,才知道要安装特定版本或greater 的 phantomjs 和 Python.我这边主要是没装python. ...

  5. ITextSharp使用说明 (转)

    原文: http://www.cnblogs.com/LifelongLearning/archive/2010/12/28/1919138.html TextSharp是一个生成Pdf文件的开源项目 ...

  6. Unity Shader入门精要读书笔记(三)Shader必须的数学基础

    Xyz三维坐标系如下:左手坐标系 但是摄像机观察空间则是采用右手系: 右手法则判断叉乘的结果的方向: 正交矩阵(单位互相垂直的基矢量构成正交矩阵)具有逆与转置一致性: 列矩阵运算CBAv和行矩阵的运算 ...

  7. java成神之——jaxb操作xml的基本使用

    JAXB 依赖 读取xml配置 写配置 自定义写配置 结语 JAXB 依赖 <dependency> <groupId>javax.activation</groupId ...

  8. MongoDB在Windows下的环境配置和使用

    总是觉得配置环境是一个超级麻烦的事情啊,而且网上说的又比较乱,配置完后又没有说怎么开始运行,在哪输入增删改查语句,像突然断层一样.所以就在这里详细说说. 一:下载安装 1.去官网的下载页面 2.下载完 ...

  9. BurpSuite系列(十一)----Project options模块(项目选择)

    一.简介 Project options主要用来对Project的一些设置. 二.模块说明 Project options主要由五个模块组成: 1.Connections 连接2.HTTP3.SSL4 ...

  10. C51串口的SCON寄存器及工作…

    原文地址:C51串口的SCON寄存器及工作方式作者:batistar 一,串行口控制寄存器SCON 它用于定义串行口的工作方式及实施接收和发送控制.字节地址为98H,其各位定义如下表: D7 D6 D ...