복붙노트

[SPRING] Spring @RequestBody 및 Enum 값

SPRING

Spring @RequestBody 및 Enum 값

나는이 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();
    }
}

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

나는이 문제를 이해하지만 Reos enum을 가진 모든 객체가 Reos.valueof () 대신 Reos.from Text ()를 사용한다는 것을 Spring에 알리는 방법을 알고 싶었다.

이것이 가능한가?

해결법

  1. ==============================

    1.나는 내가 필요한 것을 발견했다.

    나는 내가 필요한 것을 발견했다.

    http://chrisjordan.ca/post/50865405944/custom-json-serialization-for-enums-using-jackson

    그것은 2 걸음이었다.

    그리고 그게 전부입니다.

    나는 이것이 다른 사람들이 같은 문제에 직면하도록 도울 수 있기를 바란다.

  2. ==============================

    2.나는 개인적으로 잭슨이 제공 한 JsonDeserializer를 사용하여 내 자신의 디시리얼라이저 클래스를 작성하는 것을 선호한다. 열거 형에 대한 디시리얼라이저 클래스 만 작성하면됩니다. 이 예에서 :

    나는 개인적으로 잭슨이 제공 한 JsonDeserializer를 사용하여 내 자신의 디시리얼라이저 클래스를 작성하는 것을 선호한다. 열거 형에 대한 디시리얼라이저 클래스 만 작성하면됩니다. 이 예에서 :

    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
    }
    

    그게 다야. 우리 모두 준비 됐어.

    enum에 대한 serializer가 필요한 경우에 사용합니다. JsonSerializer를 확장하고 @JsonSerialize 주석을 사용하여 serializer 클래스를 작성하면 비슷한 방식으로이 작업을 수행 할 수 있습니다.

    이게 도움이 되길 바란다.

  3. ==============================

    3.사용자 정의 fromText () 메소드를 호출하는 사용자 정의 MessageConverter를 사용해야합니다. 여기에 기사 작성 방법이 나와 있습니다.

    사용자 정의 fromText () 메소드를 호출하는 사용자 정의 MessageConverter를 사용해야합니다. 여기에 기사 작성 방법이 나와 있습니다.

    AbstractHttpMessageConverter 를 확장하고 필요한 메소드를 구현 한 다음 등록하십시오.

  4. from https://stackoverflow.com/questions/33637427/spring-requestbody-and-enum-value by cc-by-sa and MIT license