Vincent Laval
Vincent Laval

Reputation: 23

Is it a way to configure Jackson ObjectMapper to allow True/False instead true/false?

I have a malformed JSON with "key":True instead of "key":true

So I'm getting the following error :

"com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'True': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')"

I can solve my problem with replace("True", "true") on string before to parsing the JSON string.

But I would like to do this automatically with handling error or something like that. Using Jackson config. Is it possible?

private static final ObjectMapper jsonMapper;
JsonFactory f = JsonFactory.builder()
    .enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS)
    .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES)
    .build();

jsonMapper = JsonMapper.builder(f).build();

JsonNode res = jsonMapper.readTree(content)

JSON-sample:

{
  ...,
  "key" : True,
  ...
}

Upvotes: 1

Views: 578

Answers (2)

scndry
scndry

Reputation: 1

It seems you already know the answer.

You have malformed JSON, and malformed JSON IS NOT JSON.

Jackson ObjectMapper is a JSON processor.

If you want to know more detailed specification and implementation, please refer to the link below:

Upvotes: 0

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28988

What you want is inherently impossible.

The parser needs to be able to distinguish between the tokens in order to know how to deal with the next portion of JSON because different JSON-elements should be treated in a different way.

There are only two valid non-String (not enclosed in quotations marks) boolean values: true and false (and null also would be successfully parsed as false). And parsing algorithm depends on them, because it needs to be able to recognize the tokens.

boolean values represented as String, i.e. enclosed in quotations marks, are parsed in the case-insensitive manner automatically without any customization. And for non-String boolean values no formatting features which allow to tweak the behavior of the parser exist.

I'm afraid that there's no other way to solve the problem other then preprocess the JSON adjusting boolean values.

Upvotes: 1

Related Questions