我有这个枚举
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 类型的属性。
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;
}
}
最后,我有一个 Controller ,该 Controller 使用 @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枚举的对象,请使用Reos.fromText()而不是Reos.valueof()。
这可能吗?
最佳答案
我找到了我所需要的。 http://chrisjordan.ca/post/50865405944/custom-json-serialization-for-enums-using-jackson。
这是两个步骤。
@Override
public String toString() {
return text;
}
@JsonCreator
public static Reos fromText(String text)
就这样。我希望这可以帮助其他面临相同问题的人。