使用 Jackson 流式解析 Json 对象数组 [英] Use Jackson To Stream Parse an Array of Json Objects

查看:78
本文介绍了使用 Jackson 流式解析 Json 对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含对象的 json 数组的文件:

I have a file that contains a json array of objects:

[{test1":ABC"},{"test2": [1, 2, 3]}]

[ { "test1": "abc" }, { "test2": [1, 2, 3] } ]

我希望使用 Jackson 的 JsonParser 从这个文件中获取输入流,并且在每次调用 .next() 时,我希望它从数组中返回一个对象,直到它用完对象或失败.

I wish to use use Jackson's JsonParser to take an inputstream from this file, and at every call to .next(), I want it to return an object from the array until it runs out of objects or fails.

这可能吗?

用例:我有一个包含 json 数组的大文件,其中填充了大量具有不同架构的对象.我想一次获取一个对象,以避免将所有内容加载到内存中.

Use case: I have a large file with a json array filled with a large number of objects with varying schemas. I want to get one object at a time to avoid loading everything into memory.

我完全忘了提及.我的输入是随着时间的推移添加的字符串.随着时间的推移,它会慢慢积累 json.我希望能够逐个对象地解析它,从字符串中删除已解析的对象.

I completely forgot to mention. My input is a string that is added to over time. It slowly accumulates json over time. I was hoping to be able to parse it object by object removing the parsed object from the string.

但我想这并不重要!只要 jsonParser 将索引返回到字符串中,我就可以手动执行此操作.

But I suppose that doesn't matter! I can do this manually so long as the jsonParser will return the index into the string.

推荐答案

你要找的是Jackson Streaming API.这是一个使用 Jackson Streaming API 的代码片段,可以帮助您实现所需.

What you are looking for is called Jackson Streaming API. Here is a code snippet using Jackson Streaming API that could help you to achieve what you need.

JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createJsonParser(new File(yourPathToFile));

JsonToken token = parser.nextToken();
if (token == null) {
    // return or throw exception
}

// the first token is supposed to be the start of array '['
if (!JsonToken.START_ARRAY.equals(token)) {
    // return or throw exception
}

// iterate through the content of the array
while (true) {

    token = parser.nextToken();
    if (!JsonToken.START_OBJECT.equals(token)) {
        break;
    }
    if (token == null) {
        break;
    }

    // parse your objects by means of parser.getXxxValue() and/or other parser's methods

}

这篇关于使用 Jackson 流式解析 Json 对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆