GSON 解析null异常问题

Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(List.class, new JsonDeserializer<List<?>>() {
    @Override
    public List<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonArray()){
            //这里要自己负责解析了
            Gson newGson = new Gson();
            try {
                return newGson.fromJson(json,typeOfT);
            }catch (Exception e){
                return Collections.EMPTY_LIST;//解析异常返回空数组
            }
        }else {
            //和接口类型不符,返回空List
            return Collections.EMPTY_LIST;
        }
    }
}).create();
registerTypeHierarchAdapter注册一个反序列号。上面是list中值是null的问题。
int,string都可以参照上面方式处理,在deserialize中处理json数据。

Leave a Reply

Your email address will not be published. Required fields are marked *