这是实际问题的简化版本。
我有一个枚举,每个条目都有多个属性
enum MyEntries{
ENTRY1("1","property1"),
ENTRY2("2","property2"),
ENTRY3("3","property3");
private String code;
private String someProperty
public MyEntries (String code,String someProperty){
this.code=code;
this.someProperty=someProperty;
}
}
我希望此端点返回所有 MyEntries 的列表,及其代码和一些属性值
@RestController
class MyController{
@GetMapping
public List<MyEntries> getcall(){
return MyEntries.values();
}
@PostMapping
public List<MyEntries> postcall(List<MyEntries>){
return MyEntries.values();
}
}
电流输出
[
ENTRY1,
ENTRY2,
ENTRY3
]
所需输出
[
{"code":"1","someProperty":"property1"},
{"code":"2","someProperty":"property2"},
{"code":"3","someProperty":"property3"}
]
我可以通过以下方式进行邮政通话 在两个属性上添加 @JsonProperty 在枚举中创建以下@JsonCreator
@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;
}
但我无法在“获取呼叫”中收到相同的回复
您可以使用
@JsonValue
注释在枚举上定义一个方法,该方法将返回包含枚举元素内部状态的传输对象。
public enum Color {
RED(1, "red"),
GREEN(2, "green"),
BLUE(3, "blue");
private int id;
private String name;
Color(int id, String name) {
this.id = id;
this.name = name;
}
@JsonValue
public Value getValue() {
return new Value(id, name);
}
public record Value(int id, String name) {
}
}
有关更多信息,请参阅Jackson 注释示例。