복붙노트

[SPRING] 자바 8 잭슨 검증

SPRING

자바 8 잭슨 검증

나는 봄철 휴식 서비스를하고있다. 사용자는이 자바 포조로 역 직렬화 된 json 객체를 전달합니다.

public final class Request {
    private String id;
    private double code;
    private String name;

    public String getId() {
        return id;
    }

    public double getCode() {
        return code;
    }

    public String getName() {
        return name;
    }
}

따라서 사용자는 다음 json을 전달해야합니다.

{
    "id": “123457896”,
    "code": "Foo",
    "name": "test"
} 

나는 필요한 모든 필드를 만들고 싶습니다. 더 적은 것을 제공하면 예외가 발생합니다. 잭슨에게 역 직렬화시 입력을 검증하도록 지시 할 수있는 방법이 있습니까? @JsonProperty (required = true)를 시도했지만 작동하지 않습니다. 분명히 여기에서 여기에서 JsonProperty 주석은 존중되지 않는 것 같습니다.

내 컨트롤러에서 호출하는 유효성 검사기가 있습니다.

@Component
public class RequestValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }

    @Override
    public void validate(Object target, Errors errors) {
        String id = ((Request) target).getId();
        if(id == null || id.isEmpty()) {
            throw new InvalidRequestException("A valid id is missing. Please provide a non-empty or non-null id.");
        }
    }
}

그러나 그것은 모든 분야를 점검하기에는 지루하고 추악한 것처럼 보입니다. 그래서 java 8, spring boot, jackson의 최신 버전을 사용하고 있습니다. 들어오는 json 입력의 유효성을 검사하는 가장 좋은 방법은 무엇입니까? 아니면 이미 가장 최신 방식으로하고 있습니까?

해결법

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

    1.Spring Validator 방식을 사용했습니다. 또 다른 접근 방법이 있습니다.

    Spring Validator 방식을 사용했습니다. 또 다른 접근 방법이 있습니다.

    J2EE JSR-303 / JSR-349 콩 검증 API. 그것은 검증 주석 (javax의,하지 잭슨)를 제공합니다.

    여기에서 좋은 예를 보아라.

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

    2.사용자 정의 유효성 검사기가 필요하지 않습니다. 잭슨에게 던지라고 말하는 방법이 있습니다.

    사용자 정의 유효성 검사기가 필요하지 않습니다. 잭슨에게 던지라고 말하는 방법이 있습니다.

    @JsonCreator 또는 사용자 정의 생성자를 추가하기 만하면됩니다. 이 같은 것이 작동해야합니다 :

    public Request(@JsonProperty(value= "id", required = true)String id,
                   @JsonProperty(value= "code",required = true)double code,
                   @JsonProperty(value= "name",required = true)String name) {
        this.id = id;
        this.code = code;
        this.name = name;
    }
    

    전체 데모 :

    import com.fasterxml.jackson.annotation.JsonCreator;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.io.IOException;
    
    public class Main {
    
    public static void main(String[] args) throws IOException {
        test("{\"id\": \"123457896\",\"code\": 1,\"name\": \"test\"}");
        test("{\"id\": \"123457896\",\"name\": \"test\"}");
        test("{\"id\": \"123457896\",\"code\": 1, \"c\": 1,\"name\": \"test\"}");
    }
    
    public static void test(String json) throws IOException{
        ObjectMapper mapper = new ObjectMapper();
        try {
            Request deserialized = mapper.readValue(json, Request.class);
            System.out.println(deserialized);
            String serialized = mapper.writeValueAsString(deserialized);
            System.out.println(serialized);
        } catch (JsonMappingException e) {
            System.out.println(e.getMessage());
        }
    }
    
    public static class Request {
        private String id;
        private double code;
        private String name;
    
        public Request(@JsonProperty(value= "id", required = true)String id,
                       @JsonProperty(value= "code",required = true)double code,
                       @JsonProperty(value= "name",required = true)String name) {
            this.id = id;
            this.code = code;
            this.name = name;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public double getCode() {
            return code;
        }
    
        public void setCode(double code) {
            this.code = code;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Request{" +
                    "id='" + id + '\'' +
                    ", code=" + code +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    }
    

    결과:

    Request{id='123457896', code=1.0, name='test'}
    {"id":"123457896","code":1.0,"name":"test"}
    Missing required creator property 'code' (index 1)
     at [Source: {"id": "123457896","name": "test"}; line: 1, column: 34]
    Unrecognized field "c" (class Main7$Request), not marked as ignorable (3 known properties: "id", "code", "name"])
     at [Source: {"id": "123457896","code": 1, "c": 1,"name": "test"}; line: 1, column: 53] (through reference chain: Request["c"])
    
  3. ==============================

    3.Jackson 스키마 유효성 검사를 사용할 수 있습니다. schema.json을 작성하고이 스키마에 대해 들어오는 각 입력의 유효성을 검증하십시오. 자세한 내용은이 링크를 클릭하십시오. http://wilddiary.com/validate-json-against-schema-in-java/

    Jackson 스키마 유효성 검사를 사용할 수 있습니다. schema.json을 작성하고이 스키마에 대해 들어오는 각 입력의 유효성을 검증하십시오. 자세한 내용은이 링크를 클릭하십시오. http://wilddiary.com/validate-json-against-schema-in-java/

  4. ==============================

    4.생성자에서 @JsonCreator 주석을 @JsonProperty와 함께 사용하면 작동합니다. 이 대답도 확인하십시오.

    생성자에서 @JsonCreator 주석을 @JsonProperty와 함께 사용하면 작동합니다. 이 대답도 확인하십시오.

    public final class Request {
        private String id;
        private double code;
        private String name;
    
        @JsonCreator
        public Request(@JsonProperty(required = true) String id,
                       @JsonProperty(required = true) double code,
                       @JsonProperty(required = true) String name) {
            this.id = id;
            this.code = code;
            this.name = name;
        }
    
        public String getId() {
            return id;
        }
    
        public double getCode() {
            return code;
        }
    
        public String getName() {
            return name;
        }
    }
    
  5. from https://stackoverflow.com/questions/36357713/java-8-jackson-validation by cc-by-sa and MIT license