Spring @RequestBody and Enum value

前端 未结 3 1053
执念已碎
执念已碎 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 21:58

    I've found what I need. http://chrisjordan.ca/post/50865405944/custom-json-serialization-for-enums-using-jackson.

    It was 2 steps.

    1. Override the toString method of the Reos enum
    @Override
    public String toString() {
        return text;
    }
    
    1. Annotate with @JsonCreator the fromText method of the Reos enum.
    @JsonCreator
    public static Reos fromText(String text)
    

    And that's all.

    I hope this could help others facing the same problem.

    0 讨论(0)
  • 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<Reos> {
    
        @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.

    0 讨论(0)
  • 2020-12-08 22:19

    You need to use a custom MessageConverter that calls your custom fromText() method. There's an article here that outlines how to do it.

    You extend AbstractHttpMessageConverter<Reos> and implement the required methods, and then you register it.

    0 讨论(0)
提交回复
热议问题