美文网首页
FastJson反序列自动识别bean类型

FastJson反序列自动识别bean类型

作者: 任未然 | 来源:发表于2021-11-12 11:08 被阅读0次

一. 概述

今天用fastjson反序列化自动识别bean时遇到一些问题,顺便就记录下吧

二. 实战

2.1 示例

    public static void main(String[] args) {
        Base base = new Base();
        base.setSex(1);
        base.setName("wpr");

        // 转json 把类名也写入json
        String json = JSON.toJSONString(base, SerializerFeature.WriteClassName);
        System.out.println(json);

        // 反序列化自动识别类
        Base parse = (Base)JSON.parse(json);
        System.out.println(parse);
        System.out.println(parse.getClass().getName());
    }

原本信心满满 结果报错了

{"@type":"com.wpr.base.domain.Base","id":1,"name":"wpr","sex":1}
Exception in thread "main" com.alibaba.fastjson.JSONException: autoType is not support. com.ak.base.domain.Base
    at com.alibaba.fastjson.parser.ParserConfig.checkAutoType(ParserConfig.java:1026)
    at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:316)
    at com.alibaba.fastjson.parser.DefaultJSONParser.parse(DefaultJSONParser.java:1356)
    at com.alibaba.fastjson.parser.DefaultJSONParser.parse(DefaultJSONParser.java:1322)
    at com.alibaba.fastjson.JSON.parse(JSON.java:152)
    at com.alibaba.fastjson.JSON.parse(JSON.java:162)
    at com.alibaba.fastjson.JSON.parse(JSON.java:131)
    at com.ak.base.controller.TestController.main(TestController.java:56)

2.2 排错

点开ParserConfig.java:1026看看报错代码


发现配置默认是不开启自动类型支持的

2.3 正确方法

    public static void main(String[] args) {
        Base base = new Base();
        base.setId(1L);
        base.setSex(1);
        base.setName("wpr");

        // 转json 把类名也写入json
        String json = JSON.toJSONString(base, SerializerFeature.WriteClassName);
        System.out.println(json);

        // 开启自动类型
        ParserConfig globalInstance = ParserConfig.getGlobalInstance();
        globalInstance.setAutoTypeSupport(true);
        
        // 反序列化自动识别类
        Base parse = (Base)JSON.parse(json,globalInstance);
        System.out.println(parse);
        System.out.println(parse.getClass().getName());
    }

打印

{"@type":"com.wpr.base.domain.Base","id":1,"name":"wpr","sex":1}
Base(id=1, name=wpr, sex=1)
com.ak.base.domain.Base

相关文章

网友评论

      本文标题:FastJson反序列自动识别bean类型

      本文链接:https://www.haomeiwen.com/subject/algnzltx.html