主頁 > 知識庫 > 淺析ASP.NET萬能JSON解析器

淺析ASP.NET萬能JSON解析器

熱門標簽:手機地圖標注如何刪除 巫師3為什么地圖標注的財寶沒有 辦理400電話證件 外呼系統(tǒng)代理品牌 寧波自動外呼系統(tǒng)代理 世紀佳緣地圖標注怎么去掉 十堰正規(guī)電銷機器人系統(tǒng) 外呼系統(tǒng)費用一年 怎么給超市做地圖標注入駐店

概念介紹
還是先簡單說說Json的一些例子吧。注意,以下概念是我自己定義的,可以參考.net里面的TYPE的模型設計
如果有爭議,歡迎提出來探討!

1.最簡單:
{"total":0}
total就是值,值是數(shù)值,等于0

2. 復雜點
{"total":0,"data":{"377149574" : 1}}
total是值,data是對象,這個對象包含了"377149574"這個值,等于1

3. 最復雜
{"total":0,"data":{"377149574":[{"cid":"377149574"}]}}
total是值,data是對象,377149574是數(shù)組,這個數(shù)組包含了一些列的對象,例如{"cid":"377149574"}這個對象。

有了以上的概念,就可以設計出通用的json模型了。

萬能JSON源碼:

復制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
namespace Pixysoft.Json
{
    public class CommonJsonModelAnalyzer
    {
        protected string _GetKey(string rawjson)
        {
            if (string.IsNullOrEmpty(rawjson))
                return rawjson;
            rawjson = rawjson.Trim();
            string[] jsons = rawjson.Split(new char[] { ':' });
            if (jsons.Length 2)
                return rawjson;
            return jsons[0].Replace("\"", "").Trim();
        }
        protected string _GetValue(string rawjson)
        {
            if (string.IsNullOrEmpty(rawjson))
                return rawjson;
            rawjson = rawjson.Trim();
            string[] jsons = rawjson.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            if (jsons.Length 2)
                return rawjson;
            StringBuilder builder = new StringBuilder();
            for (int i = 1; i jsons.Length; i++)
            {
                builder.Append(jsons[i]);
                builder.Append(":");
            }
            if (builder.Length > 0)
                builder.Remove(builder.Length - 1, 1);
            string value = builder.ToString();
            if (value.StartsWith("\""))
                value = value.Substring(1);
            if (value.EndsWith("\""))
                value = value.Substring(0, value.Length - 1);
            return value;
        }
        protected Liststring> _GetCollection(string rawjson)
        {
            //[{},{}]
            Liststring> list = new Liststring>();
            if (string.IsNullOrEmpty(rawjson))
                return list;
            rawjson = rawjson.Trim();
            StringBuilder builder = new StringBuilder();
            int nestlevel = -1;
            int mnestlevel = -1;
            for (int i = 0; i rawjson.Length; i++)
            {
                if (i == 0)
                    continue;
                else if (i == rawjson.Length - 1)
                    continue;
                char jsonchar = rawjson[i];
                if (jsonchar == '{')
                {
                    nestlevel++;
                }
                if (jsonchar == '}')
                {
                    nestlevel--;
                }
                if (jsonchar == '[')
                {
                    mnestlevel++;
                }
                if (jsonchar == ']')
                {
                    mnestlevel--;
                }
                if (jsonchar == ',' nestlevel == -1 mnestlevel == -1)
                {
                    list.Add(builder.ToString());
                    builder = new StringBuilder();
                }
                else
                {
                    builder.Append(jsonchar);
                }
            }
            if (builder.Length > 0)
                list.Add(builder.ToString());
            return list;
        }
    }
}

復制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
namespace Pixysoft.Json
{
    public class CommonJsonModel : CommonJsonModelAnalyzer
    {
        private string rawjson;
        private bool isValue = false;
        private bool isModel = false;
        private bool isCollection = false;
        internal CommonJsonModel(string rawjson)
        {
            this.rawjson = rawjson;
            if (string.IsNullOrEmpty(rawjson))
                throw new Exception("missing rawjson");
            rawjson = rawjson.Trim();
            if (rawjson.StartsWith("{"))
            {
                isModel = true;
            }
            else if (rawjson.StartsWith("["))
            {
                isCollection = true;
            }
            else
            {
                isValue = true;
            }
        }
        public string Rawjson
        {
            get { return rawjson; }
        }
        public bool IsValue()
        {
            return isValue;
        }
        public bool IsValue(string key)
        {
            if (!isModel)
                return false;
            if (string.IsNullOrEmpty(key))
                return false;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    return submodel.IsValue();
                }
            }
            return false;
        }
        public bool IsModel()
        {
            return isModel;
        }
        public bool IsModel(string key)
        {
            if (!isModel)
                return false;
            if (string.IsNullOrEmpty(key))
                return false;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    return submodel.IsModel();
                }
            }
            return false;
        }
        public bool IsCollection()
        {
            return isCollection;
        }
        public bool IsCollection(string key)
        {
            if (!isModel)
                return false;
            if (string.IsNullOrEmpty(key))
                return false;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    return submodel.IsCollection();
                }
            }
            return false;
        }

        /// summary>
        /// 當模型是對象,返回擁有的key
        /// /summary>
        /// returns>/returns>
        public Liststring> GetKeys()
        {
            if (!isModel)
                return null;
            Liststring> list = new Liststring>();
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                string key = new CommonJsonModel(subjson).Key;
                if (!string.IsNullOrEmpty(key))
                    list.Add(key);
            }
            return list;
        }
        /// summary>
        /// 當模型是對象,key對應是值,則返回key對應的值
        /// /summary>
        /// param name="key">/param>
        /// returns>/returns>
        public string GetValue(string key)
        {
            if (!isModel)
                return null;
            if (string.IsNullOrEmpty(key))
                return null;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                    return model.Value;
            }
            return null;
        }
        /// summary>
        /// 模型是對象,key對應是對象,返回key對應的對象
        /// /summary>
        /// param name="key">/param>
        /// returns>/returns>
        public CommonJsonModel GetModel(string key)
        {
            if (!isModel)
                return null;
            if (string.IsNullOrEmpty(key))
                return null;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    if (!submodel.IsModel())
                        return null;
                    else
                        return submodel;
                }
            }
            return null;
        }
        /// summary>
        /// 模型是對象,key對應是集合,返回集合
        /// /summary>
        /// param name="key">/param>
        /// returns>/returns>
        public CommonJsonModel GetCollection(string key)
        {
            if (!isModel)
                return null;
            if (string.IsNullOrEmpty(key))
                return null;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    if (!submodel.IsCollection())
                        return null;
                    else
                        return submodel;
                }
            }
            return null;
        }
        /// summary>
        /// 模型是集合,返回自身
        /// /summary>
        /// returns>/returns>
        public ListCommonJsonModel> GetCollection()
        {
            ListCommonJsonModel> list = new ListCommonJsonModel>();
            if (IsValue())
                return list;
            foreach (string subjson in base._GetCollection(rawjson))
            {
                list.Add(new CommonJsonModel(subjson));
            }
            return list;
        }
 

        /// summary>
        /// 當模型是值對象,返回key
        /// /summary>
        private string Key
        {
            get
            {
                if (IsValue())
                    return base._GetKey(rawjson);
                return null;
            }
        }
        /// summary>
        /// 當模型是值對象,返回value
        /// /summary>
        private string Value
        {
            get
            {
                if (!IsValue())
                    return null;
                return base._GetValue(rawjson);
            }
        }
    }
}


使用方法

public CommonJsonModel DeSerialize(string json)
{
 return new CommonJsonModel(json);
}

超級簡單,只要new一個通用對象,把json字符串放進去就行了。

針對上文的3個例子,我給出3種使用方法:

{"total":0}
CommonJsonModel model = DeSerialize(json);
model.GetValue("total") // return 0
{"total":0,"data":{"377149574" : 1}}
CommonJsonModel model = DeSerialize(json);
model.GetModel("data").GetValue("377149574") //return 1
{"total":0,"data":{"377149574":[{"cid":"377149574"}]}}
CommonJsonModel model = DeSerialize(json);
model.GetCollection("377149574").GetCollection()[0].GetValue("cid") //return 377149574

這個有點點復雜,

1. 首先377149574代表了一個集合,所以要用model.GetCollection("377149574")把這個集合取出來。

2. 其次這個集合里面包含了很多對象,因此用GetColllection()把這些對象取出來

3. 在這些對象List里面取第一個[0],表示取了":{"cid":"377149574"}這個對象,然后再用GetValue("cid")把對象的值取出來。

您可能感興趣的文章:
  • asp.net(C#)解析Json的類代碼
  • asp.net中各種類型的JSON格式化
  • asp.net MVC下使用rest的方法
  • .Net整合Json實現(xiàn)REST服務客戶端的方法詳解

標簽:泰州 山西 牡丹江 通遼 景德鎮(zhèn) 嘉興 天門

巨人網(wǎng)絡通訊聲明:本文標題《淺析ASP.NET萬能JSON解析器》,本文關鍵詞  淺析,ASP.NET,萬能,JSON,解析,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《淺析ASP.NET萬能JSON解析器》相關的同類信息!
  • 本頁收集關于淺析ASP.NET萬能JSON解析器的相關信息資訊供網(wǎng)民參考!
  • 推薦文章