杰克逊映射器 - 如何在null或空值上失败

时间:2017-09-24 09:54:42

标签: java jackson deserialization mapper

我们在代码中使用Jackson JSON映射器来反序列化某些配置对象。当特定字段缺失或空白时,我们希望杰克逊在反序列化时失败

杰克逊支持这种行为的唯一特征是基元:

final DeserializationConfig.Feature failOnPremitives = DeserializationConfig.Feature.FAIL_ON_NULL_FOR_PRIMITIVES;

事情是有问题的字段主要是字符串

非常感谢任何帮助

4 个答案:

答案 0 :(得分:1)

有一个名为FAIL_ON_NULL_FOR_CREATOR_PARAMETERS的选项。

所以我认为它可以在DeserializationConfig.Feature.FAIL_ON_NULL_FOR_CREATOR_PARAMETERS;

访问

yml

jackson:
    serialization:
      indent-output: false
    deserialization:
      fail-on-unknown-properties: true
      fail-on-missing-creator-properties: true
      fail-on-null-creator-properties: true

这适用于所有类型,字符串,整数,双打等。

答案 1 :(得分:0)

您考虑过Bean Validation吗?

虽然杰克逊专注于JSON解析,但Bean验证就是在bean上声明并执行验证。

您可以使用来自@NotNull@NotBlankHibernate Validator,即Bean验证参考实现。

或者您可以使用JSON Schema

答案 2 :(得分:0)

必须创建特定于对象的自定义反序列化器。

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;

class JacksonDeserializerTest {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule("CustomPersonDeserializer", new Version(1, 0, 0, null, null, null));
        module.addDeserializer(Person.class, new CustomPersonDeserializer());
        mapper.registerModule(module);

        String jsonString = "{ \"id\": 1, \"name\": \"User 1 \"}";
        Person user = mapper.readValue(jsonString, Person.class);
        System.out.println("User: " + user.toString());

        jsonString = "{ \"id\": 1}";
        user = mapper.readValue(jsonString, Person.class);
    }

    static class CustomPersonDeserializer extends StdDeserializer<Person> {

        private static final long serialVersionUID = -4100181951833318756L;

        public CustomPersonDeserializer() {
            this(null);
        }

        public CustomPersonDeserializer(Class<?> vc) {
            super(vc);
        }

        @Override
        public Person deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException, JsonProcessingException {
            Person person = new Person();
            ObjectCodec codec = parser.getCodec();
            JsonNode node = codec.readTree(parser);

            JsonNode idNode = node.get("id");
            int id = idNode.asInt();
            person.setId(id);

            JsonNode nameNode = node.get("name");
            if(nameNode == null){
                throw new IOException("name must be provided");
            }

            String name = nameNode.asText();
            if (name.trim().length() < 1){
                throw new IOException("name can not be empty");
            }

            person.setName(name);
            return person;
        }
    }

    static class Person {
        private int id;
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", id=" + id +
                    '}';
        }
    }
}

答案 3 :(得分:0)

替代方法:
这同样适用于对象

ObjectMapper mapper= new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);