Search code examples
javajacksonfasterxml

Deserializing json response to custom enum value in java


I am trying to deserialize a JSON response with custom enum values, but instead of mapping with the custom value, the enum is being set with its ordinal value. I have searched a lot and I can not figure out what I am doing wrong. Any help would be great.

The response is

{"id":12, "status":1}

Corresponding enum object and enum is

public class Car {
   int id;
   CarStatus status;
}


public enum CarStatus {
    
    READY(1),
    WAITING(2);

    private int value;

    CarStatus(int value) {
        this.value = value;
    }

    @JsonValue
    public int getValue() {
        return value;
    }

}

The status is set to WAITING, but I expect it to be set to READY.


Solution

  • your enum miss @JsonCreator

    try like this:

    public enum CarStatus {
        
        READY(1),
        WAITING(2);
    
        private int value;
    
        CarStatus(int value) {
            this.value = value;
        }
    
        @JsonValue
        public int getValue() {
            return value;
        }
    
        @JsonCreator
        public static CarStatus getItem(int code){
            for(CarStatus item : values()){
                if(item.getValue() == code){
                    return item;
                }
            }
            return null;
        }
    }
    

    you can see my code in github: https://github.com/onemaomao/java-common-mistakes/tree/master/src/main/java/org/geekbang/time/questions/stackoverflow/reslove/q1