Jackson Streaming API to read and write JSON
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.
JsonGenerator– Write to JSON.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.
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"
}
- Token 1 = “{“
- Token 2 = “name”
- Token 3 = “mkyong”
- 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();
}
}
}
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
Jackson Streaming API to read and write JSON的更多相关文章
- salesforce零基础学习(八十五)streaming api 简单使用(接近实时获取你需要跟踪的数据的更新消息状态)
Streaming API参考链接: https://trailhead.salesforce.com/en/modules/api_basics/units/api_basics_streaming ...
- 【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 ...
- Update-Package : Unable to load the service index for source https://api.nuget.org/v3/index.json.
由于更改了项目"属性"的"目标框架"(原来的框架是".NET Frameword4.5"改为了".NET Frameword4&q ...
- Jackson学习二之集合类对象与JSON互相转化--转载
原文地址:http://lijingshou.iteye.com/blog/2003059 本篇主要演示如何使用Jackson对List, Map和数组与JSON互相转换. package com.j ...
- 解决Nuget:https://api.nuget.org/v3/index.json 访问不了的问题
最近在家中用使用VS编译项目时,Nuget包一直下载不了,直接在浏览器中访问https://api.nuget.org/v3/index.json ,浏览器也打不开网址.把https协议改成http协 ...
- 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. 却报如下错 ...
- Twitter REST API, Streaming API
原文链接 用Twitter自己的话来说: REST API The REST API provides simple interfaces for most Twitter f ...
- 基于Woodstox的StAX 2 (Streaming API for XML)解析XML
StAX (Streaming API for XML)面向流的拉式解析XML,速度快.占用资源少,非常合适处理大数据量的xml文件. 详细教程和说明可以参见以下几篇文章: 使用 StAX 解析 XM ...
- nuget.org 无法加载源 https://api.nuget.org/v3/index.json 的服务索引
今天添加新项目想添加几个工具包,打开NuGet就这样了 发生错误如下: [nuget.org] 无法加载源 https://api.nuget.org/v3/index.json 的服务索引. 响应 ...
随机推荐
- css控制div下图片自适应解决方法:图片不超过最大宽度
我们(特别是像我一样的菜鸟)经常会遇到一个问题——图片自适应.这个问题是很普遍的.在文章区,在论坛,可以这么说:哪儿需要上传图片,哪儿就存在这个问题,而论坛上也不时有人询问.为什么?原因很简单,我们不 ...
- 使用Inno SetUp脚本打包Winform程序
在开发桌面程序时,往往需要用到打包工具将程序打包为exe可执行文件. 之前在项目中用了下 InstallShield Limited Edition for Visual Studio 2015,它 ...
- What’s that ALUA exactly?
What’s that ALUA exactly? 29 September, 20098 Comments Of course by now we have all read the excelle ...
- NOIP2005普及组第3题 采药 (背包问题)
NOIP2005普及组第3题 采药 时间限制: 1 Sec 内存限制: 128 MB提交: 50 解决: 23[提交][状态][讨论版][命题人:外部导入] 题目描述 辰辰是个天资聪颖的孩子,他的 ...
- 分析java类的静态成员变量初始化先于非静态成员变量
依上图中当class字节码文件被jvm虚拟机加载到内存中依次经过 连接 验证:对字节码进行验证 准备:给静态变量分配内存并赋予变量类型各自的默认值(注:基本类型为0或false,对象为null,sta ...
- oracle下载地址
12c 下载地址 http://www.oracle.com/technetwork/cn/database/enterprise-edition/downloads/index.html
- 爬了个爬(三)Scrapy框架
参考博客:武Sir Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取 (更确切来说, 网络抓取 ...
- IntelliJ IDEA 安装 Julia 插件
打开 IntelliJ IDEA 点击 Configure 选择 Plugins 然后点击 Browse repositories 搜索 Julia,然后点击 Install 进行安装 安装完重启一下 ...
- kali下安装go环境
1.安装go 下载安装包,命令:wget -c https://storage.googleapis.com/golang/go1.8.3.linux-amd64.tar.gz 下载完后,解压到 /u ...
- Delphi.NET
Delphi.NET Borland.VclDSnap.dll Borland.Vcl.TCustomClientDataSet TFieldType.ftBCD Borland.Vcl.TField ...