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 的服务索引. 响应 ...
随机推荐
- fragment在水平/垂直时的应用
直接看代码 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedIns ...
- php写入、追加写入文件的实例
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $t ...
- mysql实战优化之五: 更新/插入优化 sql优化
通常情况下,当访问某张表的时候,读取者首先必须获取该表的锁,如果有写入操作到达,那么写入者一直等待读取者完成操作(查询开始之后就不能中断,因此允许读取者完成操作).当读取者完成对表的操作的时候,锁就会 ...
- codeforce 985A Chess Placing(暴力)
Chess Placing time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- CentOS7 日期时间设置
1.设置系统时间为中国时区并启用NTP同步 yum install ntp //安装ntp服务 systemctl enable ntpd //开机启动服务 systemctl start ntpd ...
- git版本控制-详细操作
- git,软件帮助使用者进行版本的管理 阶段一git 命令: git init 初始化 git config --global user.email "you@example.com&qu ...
- oracle记录错误存储过程
CREATE OR REPLACE PROCEDURE SP_ERROR_LOGS_PRO(v_pro_name VARCHAR2, v_step_name VARCHAR2, v_date VARC ...
- BugkuCTF WEB
web2 打开链接,一大堆表情 查看源代码 得到 flag 文件上传测试 打开链接 选择 1 个 jpg 文件进行上传,用 burp 抓包改包 将 php 改为 jpg,发包 得到 flag 计算器 ...
- java 调用系统外部的某个程序
有时候我们java 调用系统外部的某个程序 可能需要调用系统外部的某个程序,此时就可以用Runtime.getRuntime().exec()来调用,他会生成一个新的进程去运行调用的程序. 此方法返回 ...
- Java发送邮件Utils
/** * 类文件说明 * */ public class SendMail { Logger log = Logger.getLogger(SendMail.class); /** * 发送邮件 * ...