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. mysql时间运算

    DELETE FROM zhongqiu WHERE caretatime<=ADDDATE(NOW(),-14) caretatime` timestamp NOT NULL DEFAULT ...

  2. textView 添加超链接(两种实现方式)

    在textView添加超链接,有两种方式,第一种通过HTML格式化你的网址,一种是设置autolink,让系统自动识别超链接,下面为大家介绍下这两种方法的实现 在textView添加超链接,有两种方式 ...

  3. ssh面试题2

    1. BeanFactory的作用是什么? [中] BeanFactory是配置.创建.管理bean的容器,有时候也称为bean上下文.Bean与bean的依赖关系,也是由BeanFactory负责维 ...

  4. SVN报错:sqlite[S5]:database is locked

    昨天下午修改几个冲突的jar包后提交svn后报错,接下来svn操作就失灵了,无论是clean up还是revert还是release lock都无济于事.解决办法: 首先下载sqlite3,我的是64 ...

  5. RK3288 模块单独编译

    模块以Email为例: 1.执行build目录下的脚本文件envsetup.sh $ source ./build/envsetup.sh 2.选择版本(user为用户版本   eng为工程版本) $ ...

  6. Indy10收发Hotmail邮件

    hotmail开放了pop3,可以使用客户端工具收取邮件了. POP 服务器: pop3.live.com (端口 995)需要 POP SSL?: 是的用户名: Windows Live ID, 比 ...

  7. java从键盘输入一组数据,输出其最大值,平均值,最小值没法输出

    总结::需要耐心,加思考.做事不思考,那就是白做徒劳!!!!! package com.aini; import java.util.Scanner; //操...为什么数组的大小比较我硬是搞不懂,比 ...

  8. phpmailer实现邮件发送

    phpmailer实现邮件发送 1.代码 <?php require("class.phpmailer.php"); //这个是一个smtp的php文档,网上可以下载得到 $ ...

  9. 使用ResultSet结果集查询数据

    直接上下代码: package com.learn.jdbc.chap05; import java.sql.Connection; import java.sql.PreparedStatement ...

  10. 微信小程序wxss设置样式

    微信小程序wxss设置样式 对于以前搞客户端开发的来说,有着客户端的逻辑,就是不知道怎么设置样式,把对应的控件显示出来 一.wxml 界面结构wxmL比较容易理解,主要是由八大类基础组件构成: 一.视 ...