views:

22

answers:

1

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.

A: 

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.

StaxMan
Actually, come to think of that, no, it won't be easy to add. Simple look-ahead won't work due to separators (commas, colons). So getting it added is probably not very easy.
StaxMan