mam ten enumWiosna @RequestBody i wartość Enum
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();
}
}
I klasy o nazwie Review, klasa ta zawiera właściwość typu wyliczenia 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;
}
}
Wreszcie Mam kontroler, który odbiera przeglądu obiektów z @RequestBody.
@RestController
public class ReviewController {
@RequestMapping(method = RequestMethod.POST, value = "/reviews")
@ResponseStatus(HttpStatus.CREATED)
public void saveReview(@RequestBody Review review) {
reviewRepository.save(review);
}
}
Gdybym wywołać kontrolera z
{"reos":"VALUE1"}
Nie ma problemu, ale gdy przywołuję z
{"reos":"A"}
otrzymuję ten błąd
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: [email protected]; 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: [email protected]; line: 1, column: 40] (through reference chain: com.microservices.Review["reos"])"
I undertand problem, ale chciałem wiedzieć sposób powiedzieć Spring, że dla każdego obiektu z Reos enum użyj Reos.fromText() zamiast Reos.valueof().
Czy to możliwe?
Adnotacja JsonCreator (krok 2) rozwiązała problem, nad którym pracowałem. Niezła odpowiedź. –