question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Deserializing enum error by using int/Integer value with @JsonValue

See original GitHub issue

When annotating @JsonValue on the int/Integer value, the enum can be serialized as number successfully. when i deserializing it by using a number JSON string, it will throw exception.

But it work well when using a ‘String’ type JSON string.

Whether the type of serialized values and deserialized parameters should be consistent?

follow is some sample code:

public class Test {
    public static void main(String[] args) {
        final ObjectMapper mapper = new ObjectMapper();

        try {
            // work well as "10" JSON string
            ColorEnum colorEnum1 = mapper.readValue("\"10\"", ColorEnum.class);
            System.out.println(colorEnum1);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        try {
            // fail as 10 JSON string
            ColorEnfum colorEnum2 = mapper.readValue("10", ColorEnum.class);
            System.out.println(colorEnum2);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            // fail when using serialized generated string
            String json = mapper.writeValueAsString(ColorEnum.RED);
            ColorEnum colorEnum3 = mapper.readValue(json, ColorEnum.class);
            System.out.println(colorEnum3);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    enum ColorEnum {
        RED(10),
        YELLOW(20),
        GREEN(30);

        ColorEnum(Integer value) {
            this.value = value;
        }

        @JsonValue
        private final Integer value;

        public Integer getValue() {
            return value;
        }
    }
}

the result is:

RED
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `cn.zzzzbw.springboot.Test$ColorEnum` from number 10: index value outside legal index range [0..2]
 at [Source: (String)"10"; line: 1, column: 1]
	at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)
	at com.fasterxml.jackson.databind.DeserializationContext.weirdNumberException(DeserializationContext.java:1710)
	at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdNumberValue(DeserializationContext.java:992)
	at com.fasterxml.jackson.databind.deser.std.EnumDeserializer.deserialize(EnumDeserializer.java:200)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4482)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3434)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3402)
	at cn.zzzzbw.springboot.Test.main(Test.java:23)
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `cn.zzzzbw.springboot.Test$ColorEnum` from number 10: index value outside legal index range [0..2]
 at [Source: (String)"10"; line: 1, column: 1]
	at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)
	at com.fasterxml.jackson.databind.DeserializationContext.weirdNumberException(DeserializationContext.java:1710)
	at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdNumberValue(DeserializationContext.java:992)
	at com.fasterxml.jackson.databind.deser.std.EnumDeserializer.deserialize(EnumDeserializer.java:200)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4482)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3434)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3402)
	at cn.zzzzbw.springboot.Test.main(Test.java:31)

Process finished with exit code 0

ps: the version is 2.11.0

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
zzzzbwcommented, Jun 10, 2020

This really works using static factory method with @JsonCreator.

But threre are a lot of enum like this in my project. The factory method is static mean can‘t be inherit so that i have to write manually for every enum.

Thanks very much if can solve this problem in the next version

0reactions
cowtowncodercommented, Feb 20, 2021

Realized that this is a duplicate of #1850 so closing in favor of that one.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Jackson: Serialize and deserialize enum values as integers
It should work by specifying JsonValue mapper. public enum State { OFF, ON, UNKNOWN; @JsonValue public int toValue() { return ordinal(); } }....
Read more >
How To Serialize and Deserialize Enums with Jackson
This is possible because Enum values are constants. First, let's use @JsonValue with one of the getter methods, getMeters(): public enum ...
Read more >
Serialize and Deserialize Enums with Jackson - Javatpoint
The @JsonValue annotation is one of the annotations which we can use for both serializing and deserializing enums. Enum values are constants, and...
Read more >
DeserializationFeature (jackson-databind 2.6.0 API) - FasterXML
Feature that determines whether JSON integer numbers are valid values to be used for deserializing Java enum values. FAIL_ON_READING_DUP_TREE_KEY.
Read more >
Deserializing an enum with int values - Flexjson - SourceForge
But one thing doesn't: Enum values that are sent as an integer, ... .use(Enum.class, OurEnumTransformer), if we don't we get an error like:...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found