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

查看:137
本文介绍了使用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天全站免登陆