Abhinav Manthri
Abhinav Manthri

Reputation: 348

Is there way to deserialise {"number1":5L,"number2":5L} to a class having long fields?

When I deserialise JSON:

{"number1":5L,"number2":5L}

to a class having long fields, I get below error:

JsonParseException: Unexpected character ('L' ): was expecting comma to separate Object entries

How to fix it?

Upvotes: 1

Views: 159

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38645

JSON payload is not valid. Number can not be represented with letter L at the end. See below chart:

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Above picture comes from json.org. To handle invalid JSON we need to implement custom deserialiser for Long class:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.NumberDeserializers;

import java.io.File;
import java.io.IOException;
import java.util.StringJoiner;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        Id id = mapper.readValue(jsonFile, Id.class);
        System.out.println(id);
    }
}

class LongJsonDeserializer extends JsonDeserializer<Long> {


    private final NumberDeserializers.LongDeserializer longDeserializer = new NumberDeserializers.LongDeserializer(Long.TYPE, 0L);

    @Override
    public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        Long value = longDeserializer.deserialize(p, ctxt);
        goToNextTokenSilently(p);
        return value;
    }

    private void goToNextTokenSilently(JsonParser p) {
        try {
            p.nextToken();
        } catch (Exception e) {
            //log if needed
        }
    }
}

class Id {

    @JsonDeserialize(using = LongJsonDeserializer.class)
    private Long number1;

    @JsonDeserialize(using = LongJsonDeserializer.class)
    private Long number2;

    // getters, setters, toString
}

Upvotes: 0

Related Questions