在json获得反序列化时添加validaitons jackson

时间:2015-12-29 21:24:32

标签: java json jackson

我有一个json结构,如下所示:

{
    "clientId": 111,
    "clientName": "abc",
    "holder": [
        {
            "clientKey": "abc1",
            "clientValue": {"hello" : "world"}
        },
        {
            "clientKey": "abc2",
            "recordValue": {}
        }
    ]
}

我使用Jackson将我的上述JSON反序列化到我的POJO。下面是我的POJO类,其中所有内容都将被序列化。

import org.codehaus.jackson.annotate.JsonProperty;

public class DataRequest {

    @JsonProperty("clientId")
    private int clientId;

    @JsonProperty("clientName")
    private String clientName;

    @JsonProperty("holder")
    private List<ClientHolder> holder;

    // getters and setters

    public static class ClientHolder {
        @JsonProperty("clientKey")
        private String clientKey;

        @JsonProperty("clientValue")
        private Map<String, Object> clientValue;

        // getters and setters
    }
}

有没有什么方法可以让我在jackson中有一些注释可以在进行反序列化时进行验证,而不是在所有反序列化后进行验证检查?我想验证以下内容:

  • clientId应大于零。
  • clientName永远不应为null或空字符串。
  • holder列表永远不应为空。
  • clientKey永远不应为null或空字符串。
  • clientValue也不应为空或空。

现在我在这里验证:

private void validate(DataRequest request) {
    if (request.getSchemaId() <= 0) {
        // throw some exception
    }

    if (request.getClientName() == null || request.getClientName().isEmpty()) {     
        // throw some exception
    }

    // now I am not sure how should I do the validation for each 
    // clientKey and clientValue here efficiently 
    // if this is the only way we can do validations
}

1 个答案:

答案 0 :(得分:0)

您可以考虑使用the Jackson Builder pattern support来构建模型。然后,您可以将验证代码放在构建器的构建方法中。构建方法将被称为反序列化的一部分。以下是Jackson 2.X的完整示例。

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class JacksonBuilderValidation {

    final static String JSON = "{\n"
            + "    \"clientId\": 111,\n"
            + "    \"clientName\": \"abc\",\n"
            + "    \"recordValue\": [\n"
            + "        {\n"
            + "            \"clientKey\": \"abc1\",\n"
            + "            \"clientValue\": {\"hello\" : \"world\"}\n"
            + "        },\n"
            + "        {\n"
            + "            \"clientKey\": \"abc2\",\n"
            + "            \"clientValue\": {}\n"
            + "        }\n"
            + "    ]}";
    @JsonDeserialize(builder = JacksonBuilderValidation.DataRequest.Builder.class)
    static class DataRequest {
        private int clientId;
        private String clientName;
        private List<ClientHolder> recordValue;

        private DataRequest(Builder builder) {
            this.clientId = builder.clientId;
            this.clientName = builder.clientName;
            this.recordValue = builder.recordValue;
        }

        @Override
        public String toString() {
            return "DataRequest{" +
                    "clientId=" + clientId +
                    ", clientName='" + clientName + '\'' +
                    ", recordValue=" + recordValue +
                    '}';
        }

        static class ClientHolder {
            public String clientKey;
            public Map<String, Object> clientValue;

            @Override
            public String toString() {
                return "ClientHolder{" +
                        "clientKey='" + clientKey + '\'' +
                        ", clientValue=" + clientValue +
                        '}';
            }
        }

        @JsonPOJOBuilder(withPrefix = "")
        static class Builder {
            private int clientId;
            private String clientName;
            private List<ClientHolder> recordValue;

            Builder clientId(int clientId) {
                this.clientId = clientId;
                return this;
            }

            Builder clientName(String clientName) {
                this.clientName = clientName;
                return this;
            }

            Builder recordValue(List<ClientHolder> recordValue) {
                this.recordValue = recordValue;
                return this;
            }

            DataRequest build() {
                final DataRequest dataRequest = new DataRequest(this);
                // write validation code here
                System.out.println("Is record value empty? "
                        + dataRequest.recordValue.isEmpty());
                return dataRequest;
            }
        }
    }

    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(JSON, DataRequest.class));
    }

}

输出:

Is record value empty? false
DataRequest{clientId=111, clientName='abc', recordValue=[ClientHolder{clientKey='abc1', clientValue={hello=world}}, ClientHolder{clientKey='abc2', clientValue={}}]}