如何序列化含多属性的Java Enum?Get接口返回格式异常问题
解决Spring Boot枚举GET接口返回格式问题
问题原因
默认情况下Jackson会将枚举序列化为枚举名称(如ENTRY1),你配置的@JsonCreator和@JsonProperty仅处理反序列化(对应POST接口接收参数的场景),并未改变枚举的序列化规则,因此GET接口仍返回枚举名称列表。
解决方案
在枚举类上添加@JsonFormat(shape = JsonFormat.Shape.OBJECT)注解,强制Jackson将枚举当作普通Java对象序列化,输出指定属性的键值对。
修改后的枚举代码
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; @JsonFormat(shape = JsonFormat.Shape.OBJECT) enum MyEntries { ENTRY1("1", "property1"), ENTRY2("2", "property2"), ENTRY3("3", "property3"); @JsonProperty("code") private String code; @JsonProperty("someProperty") private String someProperty; MyEntries(String code, String someProperty) { this.code = code; this.someProperty = someProperty; } @JsonCreator public static MyEntries fromValue(@JsonProperty("code") String a, @JsonProperty("someProperty") String b) { for (MyEntries entry : MyEntries.values()) { if (entry.code.equals(a) && entry.someProperty.equals(b)) { return entry; } } return null; } // 可选:添加getter方法,让序列化更规范(若Jackson配置允许访问私有字段则可省略) public String getCode() { return code; } public String getSomeProperty() { return someProperty; } }
效果说明
修改后,GET接口返回的响应将变为你期望的格式:
[ {"code":"1","someProperty":"property1"}, {"code":"2","someProperty":"property2"}, {"code":"3","someProperty":"property3"} ]
同时POST接口的反序列化功能不受影响,仍可正常接收参数。
内容的提问来源于stack exchange,提问作者MPS
相关产品推荐
相关产品推荐

