Json数据格式序列化小窍门

2019-11-21  本文已影响0人  极无宪

在调用以json数据类型的数据接口中,常常需要将实体数据序列化与反序列化为实体数据,常常需要定义好多实体类来封装数据。比如要接入新的一家数据接口的话,可能每个接口就需要定义一个实体类,对于复杂的数据格式可能一个接口需要定义多个实体类!那么有么有什么方法可以减少实体类的定义吗?为了不定义那么多实体类,减少实体类定义有什么方法吗?

在C#中可以使用Dictionary<string,object>这个类;如果是Java的话,可以用map这个类。每一条数据对应一个Dictionary<string,object>,如果是数组的话,可以放在List<Dictionary<string,object>>里面或者直接使用数组,再转换成json格式的数据。他的结果同定义实体类的结果是一模一样的,这样我们就可以不用定义那么多实体类了,提高工作效率,减少定义一大堆实体类来存储这些数据。以下是例子:
这个是原来的接口需要定义的一个复杂的实体类用来封装数据

public class DocsInputBody
{
    public class DocListItem
    {
        public DocListItem()
        {
        meta = new BDFJSON.Meta();
        }
        public string collkey { get; set; }
        public string uri { get; set; }
        public BDFJSON.Meta meta { get; set; }
    }
    public class Root
    {
        public Root()
        {
            docList = new List<DocListItem>();
            local = false;
            customerId = "xxxxxxxxxxxxxxxxxx";
            collectionName = "xxxx";
            maxTagNum = "xxxx";
            type="xxxx";
            alias="xxxx";
            queryNets=new List<QueryNetsItem>  ();
            queryNets.Add(new  QueryNetsItem ()); 
        }
        public string collectionName { get; set; }
        public string customerId { get; set; }
        public bool local { get; set; }
        public List<DocListItem> docList { get; set; }
        public string maxTagNum { get; set; }
        public string type { get; set; }
        public string alias { get; set; }
        public List<QueryNetsItem> queryNets { get; set; }
    }
    public class QueryNetsItem
    {
        public QueryNetsItem()
        {
            type = "xxxx";
            alias = "xxxx";
        }
        public string type { get; set; }
        public string alias { get; set; }
    }
}

如果采用Dictionary<string,object>,我们封装Root这个实体类的时候只需要

Dictionary<string, object> datas = new Dictionary<string, object>();
datas.Add("collectionName","xxxxx");
datas.Add("customerId","xxxxx");
datas.Add("collectionName","xxxxx");
datas.Add("local",false);
List<Dictionary<string, object>> list=new List<Dictionary<string, object>>();
datas.Add("docList",list);
datas.Add("type","xxxxx");
datas.Add("alias","xxxxx");
datas.Add("maxTagNum","xxxxx");
List<Dictionary<string, object>> listNetsItem=new List<Dictionary<string, object>>();
datas.Add("queryNets",listNetsItem);

使用Dictionary<string,object>的好处就是可以减少不必要的实体类。如果只是为了接受数据之后就不需要用到定义的实体类,可以考虑采用这种方式;如果定义的实体类在多个地方用到,为了方便使用还依旧使用定义实体类的方式。

上一篇 下一篇

猜你喜欢

热点阅读