序列化具有多个值的 Java 枚举

问题描述 投票:0回答:1

这是实际问题的简化版本。

我有一个枚举,每个条目都有多个属性

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

但我无法在“获取呼叫”中收到相同的回复

json enums marshalling jackson-databind
1个回答
0
投票

您可以使用

@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 注释示例

© www.soinside.com 2019 - 2024. All rights reserved.