开发者社区> 问答> 正文

fastjson 2 反序列化信息丢失

问题描述

简要描述您碰到的问题。 使用中发现一些类序列化为空对象,使用场景为字段都在基类中,没有set方法,仅有get,子类使用构造函数初始化字段

环境信息

OS信息: [e.g.:CentOS 8.4.2105 4Core 3.10GHz 16 GB] JDK信息: [e.g.:Openjdk 17] 版本信息:[e.g.:Fastjson2 2..0.7] 重现步骤

如何操作可以重现该问题:

interface IBase { int getId(); String getName(); } abstract class Base implements IBase { private int id; private String name; protected Base(int id, String name) { this.id = id; this.name = name; }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

class Device extends Base implements IBase {
    public Device(int id, String name) {
        super(id, name);
    }
}

interface Ixx {
    IBase getBase();
}
class Xx implements Ixx {
    private IBase base;

    public Xx(IBase base) {
        this.base = base;
    }

    public IBase getBase() {
        return base;
    }
}

var device = new Device(1, "xxx"); var xx = new Xx(device); var str = JSON.toJSONString(xx); System.out.println(str); var x = JSON.parseObject(str, Xx.class); System.out.println(x);

我在测试服务器上发现序列化为空后代码调整了,不使用接口 本机模拟时序列化没问题,反序列化时数据丢失 测试服务器为grallvm openjdk 17,本机oracle jdk 17

原提问者GitHub用户cjdxhjj

展开
收起
飘飘斯嘉丽 2023-04-21 11:31:55 283 0
1 条回答
写回答
取消 提交回答
  • 要保留类型信息,序列化的时候需要使用JSONWriter.Feature.WriteClassName),反序列化的时候需要JSONReader.Feature.SupportAutoType

    public void test() {
        Device device = new Device(1, "xxx");
        Xx xx = new Xx(device);
        String str = JSON.toJSONString(xx, JSONWriter.Feature.WriteClassName);
        System.out.println(str);
        Xx x = JSON.parseObject(str, Xx.class, JSONReader.Feature.SupportAutoType);
        assertEquals(xx.base.getClass(), x.base.getClass());
    }
    

    原回答者GitHub用户wenshao

    2023-04-21 14:32:37
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载