Java Spring自定义枚举以json序列化的字符串转换

发布于 2025-02-13 17:29:18 字数 875 浏览 0 评论 0 原文

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

示例控制器

@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”] ,尽管我希望它返回 [“ sampe”] 。有没有办法在春季实施?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

灼疼热情 2025-02-20 17:29:18

假设您正在使用默认 mappingJackson2HttpMessageConverter ,则在场景的后面使用Jackson的 Objectmapper 来执行所有JSON序列化和否定化。因此,这是为您的协议对象配置杰克逊的问题。

在这种情况下,可能是最直接的告诉杰克逊,它可以使用 myenum 的实例 @jsonvalue 注释。

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 有一个奖励,如其Javadoc中所述:

注意:当使用Java枚举时,另一项功能是,通过注释方法返回的值也被认为是从json字符串到序列化的值。这是可能的,因为一组枚举值是恒定的,并且可以定义映射,但对于POJO类型来说通常不能进行。因此,这不用于pojo。

因此,如果您的应用程序中具有相同的枚举定义,则可以将人类可读的值重新归因于您的枚举。

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.

温柔戏命师 2025-02-20 17:29:18

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

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

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

public enum MyEnum {
    ...
    @JsonValue
    public String getName() {
        return this.name;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文