Home > Net >  Java Spring custom Enum to String conversion in JSON Serialization
Java Spring custom Enum to String conversion in JSON Serialization

Time:07-06

I'm trying to convert an enum value into a custom string as part of a JSON response in a Java Spring application. I've attempted to override the enum's toString method and create a Spring converter but both attempts don't seem to work.

Sample Controller

@RequestMapping(value = "/test/endpoint", produces = APPLICATION_JSON_VALUE)
@RestController
public class RecommenderController {
    ...
    @GetMapping("test")
    public List<MyEnum> test() {
        return new ArrayList<>() {{
            this.add(MyEnum.SAMPLE);
        }};
    }
}

Enum

public enum MyEnum {
    SAMPLE("sample"), OTHER_SAMPLE("other sample");
    private final String name;
    public MyEnum(String name) {
        this.name = name;
    }
    public String toString() {
        return this.name;
    }
}

This code returns the response ["SAMPLE"] although I want it to return ["sample"]. Is there a way to implement this in Spring?

CodePudding user response:

This can be done by using the @JsonValue annotation in the enum definition:

public enum MyEnum {
    ...
    @JsonValue
    public String getName() {
        return this.name;
    }
}

CodePudding user response:

Assuming you are using the default MappingJackson2HttpMessageConverter, then behind the scenes you are using Jackson's ObjectMapper to perform all the JSON serialization and deserialization. So it's a matter of configuring Jackson for your protocol objects.

In this case, it's probably most straightforward tell Jackson that it can make a single JSON value for your instance of MyEnum with the @JsonValue annotation.

public enum MyEnum {
    SAMPLE("sample"), OTHER_SAMPLE("other sample");
    private final String name;

    public MyEnum(String name) {
        this.name = name;
    }

    @JsonValue
    public String getValue() {
        return this.name;
    }
}

@JsonValue has a bonus, as described in its Javadoc:

NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization.

So if you have the same Enum definition in your application that receives the list, it will deserialize the human readable value back into your Enum.

  • Related