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 的服务索引. 响应 ...
随机推荐
- win10笔记本用Fiddler对手机App抓包
移动客户端项目有时需要针对手机app进行抓包,这时一般有两种办法:直接下个手机抓包工具的app,在手机上抓:pc机上装上抓包工具,pc和手机连接同一个无线,在pc机上抓.第一种比较简单,但抓包工具自然 ...
- css学习笔记之图像
图像与文本的对齐方式: vertical-align:text-top;表示的意思是图像的顶部和同一行的文本对齐,但文本不会超出图片的上边线. vertical-align:middle;表示的意思是 ...
- laravel查看sql语句
我自己是用第一种方法来调试的,第三种不行 不知道为啥 laravel查看sql语句 方法一: 我们有时候想测试一段代码生产的 SQL 语句,比如: 我们想看 App\User::all(); 产生的 ...
- ONVIF、RTSP/RTP、FFMPEG的开发实录
前言 本文从零基础一步步实现ONVIF协议.RTSP/RTP协议获取IPC实时视频流.FFMPEG解码.开发环境为WIN7 32位 + VS2010. 最终成功获取浩云.海康.大华的IPC实时视频流. ...
- PS相关技术
PS相关长时间不用就忘记了,做个笔记,记录下来 (1)复制图层,可以将图层复制到另外的图层里去,这样,多个图层就可以编辑了 (2)通过建立选区,可以选择右键,通过剪切的图层,通过复制的图层将图片抠出来 ...
- 微信小程序之巧妙的封装
巧妙的封装 暴露一个访问地址xapp.config.js module.exports = { api_host: `https://a.squmo.com/yizu` } 继续引入,加暴露api.c ...
- mysql流程控制
一 流程控制 delimiter // CREATE PROCEDURE proc_if () BEGIN declare i int default 0; if i = 1 THEN SELECT ...
- temp5
- Linux日志文件查看和搜查命令(错误日志排查定位)
一.cat命令 cat 命令用于连接文件并打印到标准输出设备上,主要用来查看文件内容,创建文件,文件合并,追加文件内容等功能. 语法格式 cat [-AbeEnstTuv] fileName 参数说明 ...
- 【bzoj1015】星球大战starwar
1015: [JSOI2008]星球大战starwar Time Limit: 3 Sec Memory Limit: 162 MBSubmit: 5139 Solved: 2332[Submit ...