【问题标题】:Java Spring custom Enum to String conversion in JSON SerializationJSON序列化中Java Spring自定义枚举到字符串的转换
【发布时间】:2022-07-06 01:02:17
【问题描述】:

我正在尝试将枚举值转换为自定义字符串,作为 Java Spring 应用程序中 JSON 响应的一部分。我试图覆盖枚举的 toString 方法并创建一个 Spring 转换器,但两种尝试似乎都不起作用。

样品控制器

@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);
        }};
    }
}

枚举

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;
    }
}

此代码返回响应 ["SAMPLE"],尽管我希望它返回 ["sample"]。有没有办法在 Spring 中实现这一点?

【问题讨论】:

  • 你可以简单地返回字符串列表,而不是枚举列表
  • 这是一个最小的用例 - 枚举嵌套在其他数据类型中,我试图将其保留为枚举以消除原始痴迷

标签: java json spring enums


【解决方案1】:

这可以通过在枚举定义中使用@JsonValue 注释来完成:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多