本文介绍了Spring @RequestBody和枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个枚举

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的类,此类包含一个属性类型枚举Reos

And a class called Review, this class contains a property of the type 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

Finally I have a controller that receives an object review with the @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"}

没有问题,但是当我调用

There is not problem, but when I invoke with

{"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"])"


$ b $我想知道这个问题,但是我想知道一种告诉Spring的方法,对于Reos枚举的每个对象使用Reos.fromText()而不是Reos.valueof()。

I undertand the problem, but I wanted to know a way to tell Spring that for every object with Reos enum use Reos.fromText() instead of Reos.valueof().

这是可能吗?

推荐答案

我找到了我需要的。

这是两步。


  1. 覆盖Reos枚举的toString方法

  1. Override the toString method of the Reos enum

@Override
public String toString (){
return text;
}

@Overridepublic String toString() { return text;}

使用@JsonCreator注释Reos枚举的fromText方法。

Annotate with @JsonCreator the fromText method of the Reos enum.

@JsonCreator
public static Reo fromText(String text)

@JsonCreatorpublic static Reos fromText(String text)

这就是全部。

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

I hope this could help others facing the same problem.

这篇关于Spring @RequestBody和枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 22:20