Spring @RequestBody and Enum value

前端 未结 3 1060
执念已碎
执念已碎 2020-12-08 21:30

I Have this enum

public enum Reos {

    VALUE1(\"A\"),VALUE2(\"B\"); 

    private String text;

    Reos(String text){this.text = text;}

         


        
3条回答
  •  渐次进展
    2020-12-08 22:12

    I personally prefer writing my own deserializer class using JsonDeserializer provided by jackson. You just need to write a deserializer class for your enum. In this example:

    class ReosDeserializer extends JsonDeserializer {
    
        @Override
        public Reos deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    
            ObjectCodec oc = jsonParser.getCodec();
            JsonNode node = oc.readTree(jsonParser);
    
            if (node == null) {
                return null;
            }
    
            String text = node.textValue(); // gives "A" from the request
    
            if (text == null) {
                return null;
            }
    
            return Reos.fromText(text);
        }
    }
    

    Then, we should mark the above class as a deserializer class of Reos as follows:

    @JsonDeserialize(using = ReosDeserializer.class)
    public enum Reos {
    
       // your enum codes here
    }
    

    That's all. We're all set.

    In case if you need the serializer for the enum. You can do that in the similar way by creating a serializer class extending JsonSerializer and using the annotation @JsonSerialize.

    I hope this helps.

提交回复
热议问题