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. 关于yum

    1. yum的本地安装 yum install --downloadonly --downloaddir=/opt/software cd /opt/software yum localinstall ...

  2. SQL语言分为五大类

    SQL语言分为五大类:DDL(数据定义语言) - Create.Alter.Drop 这些语句自动提交,无需用Commit提交.DQL(数据查询语言) - Select 查询语句不存在提交问题.DML ...

  3. Oracle查询多边形对象SDO_GEOMETRY并转换为java对象举例

    最近实现了一个判断点是否与多边形交互的功能,这里的点是一个经纬度,多边形是一个区域,包含多个经纬度,最后看下这个点是否在这个区域内.就好比你打开百度地图,然后看你自己的位置(点)是不是在某个小区(多边 ...

  4. TStrings的一些技巧(转)

    TStrings是一个抽象类,在实际开发中,是除了基本类型外,应用得最多的.常规的用法大家都知道,现在来讨论它的一些高级的用法.先把要讨论的几个属性列出来:1.CommaText2.Delimiter ...

  5. asp.net数据分页方法

    /// <summary> /// 数据分页方法 /// </summary> /// <param name="PageIndex">当前页& ...

  6. 杂项-公司:摩根大通百科-un

    ylbtech-杂项-公司:摩根大通百科 摩根大通集团(JPMorgan Chase & Co,NYSE:JPM:),2000年12月由J.P.摩根公司和大通-曼哈顿公司合并而成,是美国主要的 ...

  7. cocoa 线程操作

    在Cocoa 中创建线程使用NSThread类的detachNewThreadSelector: toTarget:withObject:方法 NSPort *port1 = [NSPort port ...

  8. IDA Pro 权威指南学习笔记(二) - IDA 数据库文件

    生成数据库文件 把要分析的文件用 IDA 打开后,会生成 3 个数据库文件 扩展名分别为 .id0,id1,nam .id0 文件是一个二叉树形式的数据库 .id1 文件包含描述每个程序字节的标记 . ...

  9. 多线程博文地址 http://www.cnblogs.com/nokiaguy/archive/2008/07/13/1241817.html

    http://www.cnblogs.com/nokiaguy/archive/2008/07/13/1241817.html

  10. 【面试】D

    昨天去了慕名已久的Dell面试(Dell自2015年退出了世界500强的评比),一面基本合格,二面基本没答上... 对公司的整体印象非常好(每个人桌上都有两台很大的显示器:9:00-15:30,如果能 ...