如何在Jackson json库中做peek()?

时间:2021-02-07 07:37:10

I'm using the Streaming API JsonParser of the Jackson library to do some custom json parsing in java.

我正在使用Jackson库的Streaming API JsonParser在java中进行一些自定义json解析。

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?

有没有办法实现类似于peek()方法的功能,返回下一个标记,但光标位置不向前移动?

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.

我见过的杰克逊的代码示例使用nextToken()方法来处理上述情况,遗憾的是,它也会在流中向前移动光标。

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.

NB。对其他图书馆不感兴趣,所以没有“图书馆x做所有这一切和厨房水槽”类型的答案请。

1 个解决方案

#1


5  

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.

不,目前没有这样的功能。你可以通过使用委托包装器来做到这一点?有'org.codehaus.jackson.util.JsonParserDelegate'可以使它相对容易实现,具体取决于你想要保留的关于当前元素的信息。

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.

无论它有什么价值,都可以添加JsonParser.peek();请求此方法的最佳方式是在http://jira.codehaus.org/browse/JACKSON上提交功能请求。很可能这个功能尚未被任何人请求。

Reason this might be easy (enough) to implement is that it should only require a single character look-ahead.

这可能很容易(足够)实现的原因是它应该只需要一个字符前瞻。

#1


5  

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.

不,目前没有这样的功能。你可以通过使用委托包装器来做到这一点?有'org.codehaus.jackson.util.JsonParserDelegate'可以使它相对容易实现,具体取决于你想要保留的关于当前元素的信息。

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.

无论它有什么价值,都可以添加JsonParser.peek();请求此方法的最佳方式是在http://jira.codehaus.org/browse/JACKSON上提交功能请求。很可能这个功能尚未被任何人请求。

Reason this might be easy (enough) to implement is that it should only require a single character look-ahead.

这可能很容易(足够)实现的原因是它应该只需要一个字符前瞻。