处理Jackson意外的数据类型更改

时间:2014-05-24 09:12:35

标签: json jackson

我正在使用jackson反序列化外部API。 当有可用数据时,此API返回特定属性的JSON对象,但是当没有可用数据时,它返回空JSON数组而不是返回null。它不一致但我无能为力cz这是一个外部API。

当有数据时:

buy: {data1: value1, data2: value2}

没有数据时

buy: []

我将My Jackson映射数据类定义如下

class Test {
    @JsonProperty("buy");
    Map<String, String> buyOrders;
}

当有数据时它工作正常,我可以成功地获得反序列化的数据,但是当没有数据时,我正在

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token

这很好, 但是,当存在无效数据类型时,是否有任何注释要指定null?而不是抛出异常?

1 个答案:

答案 0 :(得分:2)

您可以编写custom deserializer,将[]视为空值。这是一个例子:

public class JacksonCustomNullDeserializer {

    public static class Test {
        final public Map<String, String> buyOrders;

        @JsonCreator
        public Test(@JsonProperty("buy")
                    @JsonDeserialize(using = MyMapDeserializer.class) Map<String, String> buyOrders) {
            this.buyOrders = buyOrders;
        }

        @Override
        public String toString() {
            return "Test{" +
                    "buyOrders=" + buyOrders +
                    '}';
        }
    }

    private static class MyMapDeserializer extends StdDeserializer<Map<String, String>> {
        protected MyMapDeserializer() {
            super(Map.class);
        }

        @Override
        public Map<String, String> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
            if (jp.getCurrentToken() == JsonToken.START_ARRAY && jp.nextToken() == JsonToken.END_ARRAY) {
                return null;
            }
            return jp.readValueAs(new TypeReference<Map<String, String>>() {});
        }
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue("{\"buy\":{\"xxx\":\"yyy\"}}", Test.class));
        System.out.println(mapper.readValue("{\"buy\":[]}", Test.class));
    }

}

输出:

Test{buyOrders={xxx=yyy}}
Test{buyOrders=null}