美文网首页
fastjson(1.2.58)支持多态结构的序列化、反序列化

fastjson(1.2.58)支持多态结构的序列化、反序列化

作者: 不存在的bug | 来源:发表于2020-02-13 23:26 被阅读0次

序列化、反序列化如下结构:

import com.alibaba.fastjson.annotation.JSONType;
import lombok.Data;
import java.io.Serializable;
import java.util.List;

@Data
public class ProductFrame implements Serializable, Cloneable {

    private int productId;
    private String productName;
    private List<ProductFrameNode> resources;


    @Data
    @JSONType(seeAlso={ProductFrameNode.DataDirNode.class, ProductFrameNode.DataFileNode.class})
    public static class ProductFrameNode implements Serializable, Cloneable {
       
        private int id;
      
        private String name;

        @Data
        @JSONType(typeName = "dataDirNode")
        public static class DataDirNode extends ProductFrameNode implements Serializable {

            private Integer nodeId;

            private Integer courseId;
           
            private List<ProductFrameNode> children;
            
        }


        @Data
        @JSONType(typeName = "dataFileNode")
        public static class DataFileNode extends ProductFrameNode implements Serializable {

            private Integer hlsType;

            private Integer nodeId;

        }

    }

}

解析示例:(和解析普通的对象结构不同)

        ProductFrame productFrame = null;
        productFrame = new ProductFrame();
        productFrame.setProductName("产品名");
        productFrame.setProductId(15509);

        List<ProductFrame.ProductFrameNode> dataDownloadNodes = new ArrayList<ProductFrame.ProductFrameNode>();

        ProductFrame.ProductFrameNode.DataDirNode dataDirNode = new ProductFrame.ProductFrameNode.DataDirNode();
        dataDirNode.setNodeId(3);
        dataDirNode.setCourseId(6);

        List<ProductFrame.ProductFrameNode> fileNodes = new ArrayList<ProductFrame.ProductFrameNode>();
        ProductFrame.ProductFrameNode.DataFileNode dataFileNode = new ProductFrame.ProductFrameNode.DataFileNode();
        dataFileNode.setHlsType(4);
        dataFileNode.setNodeId(4);
        fileNodes.add(dataFileNode);

        dataDirNode.setChildren(fileNodes);

        dataDownloadNodes.add(dataDirNode);

        productFrame.setResources(dataDownloadNodes);

        String productFrameStr = JSON.toJSONString(productFrame, SerializerFeature.WriteClassName);

        System.out.println("序列化:" + productFrameStr);

        ProductFrame dataDownload = JSON.parseObject(productFrameStr, ProductFrame.class);
        System.out.println("反序列化:" + dataDownload);

参考:
https://github.com/alibaba/fastjson/wiki/JSONType_seeAlso_cn

此类问题多在Issues中找。

相关文章

网友评论

      本文标题:fastjson(1.2.58)支持多态结构的序列化、反序列化

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