1

I'm having issues deserializing with the following code:

TokenBuffer tokenBuffer = new TokenBuffer(jp);
JsonParser jp2 = tokenBuffer.asParser();

jp2.nextToken();

JsonToken nextToken = jp2.nextToken();

if (nextToken == JsonToken.START_OBJECT) {
    return;
}

if (nextToken == JsonToken.END_OBJECT) {
    return;
}

if (jp2.currentName().equals("type")) {
    jp2.nextToken();
    attributeValueType = jp2.getValueAsString();
    break;
}

This line gives a Null pointer:

if (jp2.currentName().equals("type")) {

And this returns null:

jp2.nextToken();

And this doesn't:

jp.nextToken();

When I do the same functions on jp(so not creating jp2),everything is fine. When I switch back to Java 8, everything is fine.

Could Java 17 break the Jackson lib?

Any help is appreciated!

Michael90
  • 367
  • 3
  • 15
  • If you get a null pointer, then `jp2.currentName()` must be giving you `null`. If getting a null value there is acceptable, then you can inverse the equality check: `"type".equals(jp2.currentName())`. – Stefan Zhelyazkov Jan 11 '22 at 12:26
  • Sorry forgot to say that `jp2.nextToken()` also gives back null, but `jp.nextToken()` doesn't and `jp.currentName()` also gives back a value – Michael90 Jan 11 '22 at 13:19
  • Why do you call `jp2.nextToken()` twice? Maybe there is only one token, so the second time it quite rightly returns null. – k314159 Jan 11 '22 at 13:54

2 Answers2

1

Not sure why this works but adding this line helped:

tokenBuffer.copyCurrentStructure(jp);

So the full code now looks like this:

TokenBuffer tokenBuffer = new TokenBuffer(jp);
tokenBuffer.copyCurrentStructure(jp);
JsonParser jp2 = tokenBuffer.asParser();

jp2.nextToken();

JsonToken nextToken = jp2.nextToken();

if (nextToken == JsonToken.START_OBJECT) {
    return;
}

if (nextToken == JsonToken.END_OBJECT) {
    return;
}

if (jp2.currentName().equals("type")) {
    jp2.nextToken();
    attributeValueType = jp2.getValueAsString();
    break;
}

Like I mentioned, this is not needed when running with Java 8. It works now, so I'll close this question.

Thank you for all your help!

Michael90
  • 367
  • 3
  • 15
0

The problem is that TokenBuffer does not have access to a node from where to start parsing. Calling jp.nextToken() helps with that.

String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
JsonFactory factory = new MappingJsonFactory();
JsonParser  jp  = factory.createParser(carJson);
jp.nextToken();

TokenBuffer tb = new TokenBuffer(jp);
tb.copyCurrentStructure(jp);
JsonParser jp2 = tb.asParser();

JsonToken tok;
do {
    tok = jp2.nextToken();
    System.out.println(tok);
} while (tok != null);

You can find more information on how to use a TokenBuffer here: https://stackoverflow.com/a/41624347/9698467 and what the purpose of TokenBuffer is here: https://stackoverflow.com/a/35848619/9698467

Stefan Zhelyazkov
  • 2,599
  • 4
  • 16
  • 41