gpt4 book ai didi

json - 使用Jackson来流解析Json对象数组

转载 作者:行者123 更新时间:2023-12-03 22:48:08 26 4
gpt4 key购买 nike

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

[
{
“ test1”:“ abc”
},
{
“ test2”:[1、2、3]
}
]

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

这可能吗?

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

编辑:

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

但是我想那没关系!我可以手动执行此操作,只要jsonParser将索引返回到字符串中即可。

最佳答案

您要查找的称为Jackson Streaming API。这是使用Jackson流API的代码片段,可以帮助您实现所需的功能。

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

}

关于json - 使用Jackson来流解析Json对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24835431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com