弹簧@RequestBody和枚举值

2022-09-01 12:59:22

我有这个枚举

public enum Reos {

    VALUE1("A"),VALUE2("B"); 

    private String text;

    Reos(String text){this.text = text;}

    public String getText(){return this.text;}

    public static Reos fromText(String text){
        for(Reos r : Reos.values()){
            if(r.getText().equals(text)){
                return r;
            }
        }
        throw new IllegalArgumentException();
    }
}

还有一个名为 Review 的类,这个类包含一个 enum Reos 类型的属性。

public class Review implements Serializable{

    private Integer id;
    private Reos reos;

    public Integer getId() {return id;}

    public void setId(Integer id) {this.id = id;}

    public Reos getReos() {return reos;}

    public void setReos(Reos reos) {
        this.reos = reos;
    }
}

最后,我有一个控制器,它通过@RequestBody接收对象审查。

@RestController
public class ReviewController {

    @RequestMapping(method = RequestMethod.POST, value = "/reviews")
    @ResponseStatus(HttpStatus.CREATED)
    public void saveReview(@RequestBody Review review) {
        reviewRepository.save(review);
    }
}

如果我调用控制器

{"reos":"VALUE1"}

没有问题,但是当我调用

{"reos":"A"}

我收到此错误

Could not read document: Can not construct instance of com.microservices.Reos from String value 'A': value not one of declared Enum instance names: [VALUE1, VALUE2] at [Source: java.io.PushbackInputStream@23ce847a; line: 1, column: 40] (through reference chain: com.microservices.Review["reos"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of com.microservices.Reos from String value 'A': value not one of declared Enum instance names: [VALUE1, VALUE2] at [Source: java.io.PushbackInputStream@23ce847a; line: 1, column: 40] (through reference chain: com.microservices.Review["reos"])"

我理解了这个问题,但我想知道一种方法来告诉Spring,对于每个具有Reos枚举的对象,请使用Rees.fromText()而不是Rees.valueof()。

这可能吗?


答案 1

我找到了我需要的东西。http://chrisjordan.ca/post/50865405944/custom-json-serialization-for-enums-using-jackson

这是2个步骤。

  1. 重写 Reos 枚举的 toString 方法
@Override
public String toString() {
    return text;
}
  1. 使用@JsonCreator Reos 枚举的 fromText 方法进行批注。
@JsonCreator
public static Reos fromText(String text)

仅此而已。

我希望这可以帮助其他面临同样问题的人。


答案 2

我个人更喜欢使用 .您只需要为枚举编写一个反序列化程序类。在此示例中:JsonDeserializerjackson

class ReosDeserializer extends JsonDeserializer<Reos> {

    @Override
    public Reos deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);

        if (node == null) {
            return null;
        }

        String text = node.textValue(); // gives "A" from the request

        if (text == null) {
            return null;
        }

        return Reos.fromText(text);
    }
}

然后,我们应该将上述类标记为 Reos 的反序列化程序类,如下所示:

@JsonDeserialize(using = ReosDeserializer.class)
public enum Reos {

   // your enum codes here
}

就这样。一切准备就绪。

如果您需要 .您可以通过创建一个序列化程序类来扩展并使用注释,以类似的方式执行此操作。enumJsonSerializer@JsonSerialize

我希望这有帮助。