处理Jackson意外的数据类型更改 [英] Handle Jackson Unexpected Data Type Changes

查看:202
本文介绍了处理Jackson意外的数据类型更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using jackson to deserialize external API. This API returns JSON Object for particular property when there is data available, But when there is no data available its returning empty JSON Array instead of returning null. Its inconsistent but I can't do anything cz this is an external API.

当有数据时:

buy: {data1: value1, data2: value2}

当没有数据时

buy: []

我定义我的杰克逊映射数据类如下

I define My Jackson mapping data class as follows

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

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

When there is data it works fine and I can get deserialized data successfully, But when there is no data, I'm getting

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

完全没问题,
但是有没有注释在存在无效数据类型时指定null?而不是抛出异常?

which is perfectly fine, But Is there any annotation to assign null when there is invalid data type? instead of throwing exception ?

推荐答案

你可以写一个自定义反序列化器,它将 [] 视为空值。下面是一个示例:

You could write a custom deserializer which would treat [] as a null value. Here is an example:

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}

这篇关于处理Jackson意外的数据类型更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆