Jackson - deserialize one base enums

前端 未结 3 1555
说谎
说谎 2021-02-07 07:56

is it possible to deserialize enums, which have a one based index?

enum Status {
  Active,
  Inactive
}

{status:1} means Status.Active, but Jac

3条回答
  •  无人及你
    2021-02-07 08:24

    You can create a custom type deserialiser for your enum:

    public enum Status {
        ACTIVE,
        INACTIVE;
        public static Status fromTypeCode(final int typeCode) {
            switch(typeCode) {
            case 1: return ACTIVE;
            case 2: return INACTIVE;
            }
            throw new IllegalArgumentException("Invalid Status type code: " + typeCode);
        }
    }
    
    public class StatusDeserializer extends JsonDeserializer {
        @Override
        public Status deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
            return Status.fromTypeCode(parser.getValueAsInt());
        }
    }
    

    You can then tell Jackson to use your custom deserialiser for a property:

    public class WarpDrive {
        private Status status; 
        @JsonDeserialize(using = StatusDeserializer.class)
        public void setStatus(final Status status) {
            this.status = status;
        }
        public Status getStatus() {
            return this.status;
        }
    }
    

    You can also configure the Jackson object mapper to use your custom deserialiser for all occurrences of the target type. See http://wiki.fasterxml.com/JacksonHowToCustomDeserializers.

提交回复
热议问题