Java Spring自定义枚举以json序列化的字符串转换
我正在尝试将枚举值转换为自定义字符串,作为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”]
。有没有办法在春季实施?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您正在使用默认
mappingJackson2HttpMessageConverter
,则在场景的后面使用Jackson的Objectmapper
来执行所有JSON序列化和否定化。因此,这是为您的协议对象配置杰克逊的问题。在这种情况下,可能是最直接的告诉杰克逊,它可以使用
myenum
的实例@jsonvalue
注释。@jsonvalue
有一个奖励,如其Javadoc中所述:因此,如果您的应用程序中具有相同的枚举定义,则可以将人类可读的值重新归因于您的枚举。
Assuming you are using the default
MappingJackson2HttpMessageConverter
, then behind the scenes you are using Jackson'sObjectMapper
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.@JsonValue
has a bonus, as described in its Javadoc: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.
这可以通过在枚举定义中使用
@jsonvalue
注释来完成:This can be done by using the
@JsonValue
annotation in the enum definition: