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. eclipse 中xml文件的字体改不了

    XML Editor的改不了. 修改colors & fonts里的eclipse中打开window->prefece->generation-basic 下 Text Edito ...

  2. The type javax.xml.rpc.ServiceException cannot be resolved.It is indirectly

    The type javax.xml.rpc.ServiceException cannot be resolved.It is indirectly 博客分类: 解决方案_Java   问题描述:T ...

  3. linux(centos7) 安装nginx

    linux(centos7) 安装nginx 1.14(stable) 版本 Nginx配置文件常见结构的从外到内依次是「http」「server」「location」等等,缺省的继承关系是从外到内, ...

  4. spring的@Transactional注解详细用法(转)

    概述 事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性.Spring Framework对事务管理提供了一致的抽象,其特点如下: 为不同的事务API提供一致的编程模型, ...

  5. Avalon总线概述

    Nios系统的所有外设都是通过Avalon总线与Nios CPU相接的,Avalon总线是一种协议较为简单的片内总线,Nios通过Avalon总线与外界进行数据交换. Avalon总线接口分类 可分为 ...

  6. GOF23设计模式之单例模式(singleton)

    一.单例模式概述 保证一个类只有一个实例,并且提供一个访问该实例的全局访问点. 由于单例模式只生成一个实例,减少了系统性能开销.所以当一个对象的产生需要比较多的资源时,如读取配置.产生其他依赖对象时, ...

  7. Spring Boot Oauth2

    Oauth2是描述无状态授权的协议(授权框架),因为是无状态,所以我们不需要维护客户端和服务器之间的会话. Oauth2的工作原理: 此协议允许第三方客户端代表资源所有者访问受保护资源,Oauth2有 ...

  8. 【转】Jmeter项目测试

    Jmeter的录制回放功能是现将你对要测试的项目进行访问的历史记录进行录制,然后虚拟出多个用户对历史记录进行回放,从而达到压力测试的目的. 录制是通过代理服务器进行录制. 一.下载地址 http:// ...

  9. PHP 获取指定日期的星期几的方法

    <?php header("Content-type: text/html; charset=utf-8"); //获取星期方法 function get_week($dat ...

  10. linux那点事儿(七)----文件系统管理

    如果你是一位忠实的windows 用户,那么现在请你打开的的c盘,打开WINDWOS目录,下面存放了哪些文件和目录,相信没有人关心过吧!即便是用windows多年的人.额!其实,我也知道WINDOWS ...