如何在 Jackson json 库中执行 peek() ?
我正在使用 Streaming API JsonParser Jackson 库在 java 中进行一些自定义 json 解析。
有没有一种方法可以实现类似于 peek() 方法的功能,其中返回下一个标记但光标位置不向前移动?
其用例类似于以下内容:
JsonParser parser = new JsonFactory().createParser(inputStream);
while(parser.peek() != JsonToken.START_ARRAY){
...do something with the current token...
}
我在 Jackson 中看到的代码示例使用 nextToken()
方法来处理上述情况,不幸的是,该方法也会将光标在流中向前移动。
peek()
是否可以通过 Jackson 开箱即用,或者可以通过其他方法实现?
注意。对其他图书馆不感兴趣,所以请不要“图书馆 x 做这一切和厨房水槽”类型的答案。
I'm using the Streaming API JsonParser of the Jackson library to do some custom json parsing in java.
Is there a way of achieving functionality similar to a peek()
method, where the next token is returned but the cursor position is not moved forward?
The use case for this is similar to the following:
JsonParser parser = new JsonFactory().createParser(inputStream);
while(parser.peek() != JsonToken.START_ARRAY){
...do something with the current token...
}
The code examples I've seen for Jackson use the nextToken()
method for the above case, which unfortunately also moves the cursor forward in the stream.
Is peek()
possible with Jackson out-of-the-box, or perhaps achievable with an additional method?
NB. not interested in other libraries, so no "library x does all this and the kitchen sink" type answers please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,目前没有这样的功能。您也许可以通过使用委托包装器来做到这一点?有“org.codehaus.jackson.util.JsonParserDelegate”,它可以使其相对容易实现,具体取决于您想要保留有关当前元素的信息。
不管它的价值如何,很可能添加 JsonParser.peek() ;请求此功能的最佳方法是在 http://jira.codehaus.org/browse/ 提交功能请求杰克逊。很可能尚未有人请求此功能。
这可能很容易(足够)实现,因为它应该只需要单个字符前瞻。
No, currently there is no such functionality. You could perhaps do that by using a delegating wrapper? There is 'org.codehaus.jackson.util.JsonParserDelegate' which could make it relatively easy to implement, depending on what information you want to retain about current element.
For whatever it is worth, it might well be possible to get JsonParser.peek() added; best way to request this would be to file a feature request at http://jira.codehaus.org/browse/JACKSON. Most likely this feature hasn't been requested by anyone yet.
Reason this might be easy (enough) to implement is that it should only require a single character look-ahead.
在 jackson 2.14.x 中,您可以执行以下操作:
但是请注意,由于
JsonParser 的方式,只有当
已实现。但这至少可以涵盖很多情况。p
位于上述代码开头的数组或对象时,这才会一致地工作。 #readValueAsTree()In jackson 2.14.x you can do something like this:
Note that this however will only work consistently if
p
is at an array or object start at the beginning of the code above due to howJsonParser#readValueAsTree()
is implemented. But this will at least cover a lot of cases.