Spring @RequestBody and Enum value

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.


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.


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.