fastjson json 泛型反序列化

c0vxltue  于 2021-11-27  发布在  Java
关注(0)|答案(1)|浏览(518)

在嵌套类型的序列化时,指定具体类型没有问题,当我使用泛型的时候会抛出异常,当我在调testJson(jsonString,String.class)时会异常,我的版本是1.2.31

public static void main(String[] args) {
        ResultDTO<String> dto = new ResultDTO<>();
        dto.setSuccess(false);
        dto.setResultMessage("message");
        dto.setResultCode("code");
        dto.setResult("test string");
        String jsonString = JSON.toJSONString(dto);

        JSON.parseObject(jsonString, new TypeReference<ResultDTO<List<String>>>() {
        });
        testJson(jsonString,String.class);
    }

    public  static <T> void testJson(String jsonString,Class<T> tClass){
        JSON.parseObject(jsonString, new TypeReference<ResultDTO<List<org.apache.poi.ss.formula.functions.T>>>() {
        });
    }

异常
Exception in thread "main" com.alibaba.fastjson.JSONException: expect '[', but string, pos 23, line 1, column 24{"result":"test string","resultCode":"code","resultMessage":"message","success":false}
at com.alibaba.fastjson.parser.DefaultJSONParser.parseArray(DefaultJSONParser.java:722)
at com.alibaba.fastjson.serializer.CollectionCodec.deserialze(CollectionCodec.java:126)
at com.alibaba.fastjson.parser.deserializer.ArrayListTypeFieldDeserializer.parseArray(ArrayListTypeFieldDeserializer.java:193)
at com.alibaba.fastjson.parser.deserializer.ArrayListTypeFieldDeserializer.parseField(ArrayListTypeFieldDeserializer.java:65)
at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:822)
at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:288)
at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:687)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:378)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:346)
at com.alibaba.fastjson.JSON.parseObject(JSON.java:260)

nkhmeac6

nkhmeac61#

new TypeReference<ResultDTO<List<String>>>() {} 不应该是 new TypeReference<ResultDTO<String>>() {} 你的 ResultDTO<String> dto = new ResultDTO<>(); 定义了 String

相关问题