概念介绍
还是先简单说说Json的一些例子吧。注意,以下概念是我自己定义的,可以参考.net里面的TYPE的模型设计
如果有争议,欢迎提出来探讨!
1.最简单:
{"total":0} 
total就是值,值是数值,等于0
2. 复杂点
{"total":0,"data":{"377149574" : 1}}
total是值,data是对象,这个对象包含了"377149574"这个值,等于1
3. 最复杂
{"total":0,"data":{"377149574":[{"cid":"377149574"}]}}
total是值,data是对象,377149574是数组,这个数组包含了一些列的对象,例如{"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 List<string> _GetCollection(string rawjson)
        {
            //[{},{}]

List<string> list = new List<string>();

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 List<string> GetKeys()
        {
            if (!isModel)
                return null;

List<string> list = new List<string>();

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 List<CommonJsonModel> GetCollection()
        {
            List<CommonJsonModel> list = new List<CommonJsonModel>();

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 JSON(转http://www.360doc.com/content/14/0615/21/18155648_386887590.shtml)的更多相关文章

  1. http://www.360doc.com/content/14/0313/17/16070877_360315087.shtml

    http://www.360doc.com/content/14/0313/17/16070877_360315087.shtml

  2. http://www.360doc.com/content/13/0516/22/12094763_285956121.shtml

    http://www.360doc.com/content/13/0516/22/12094763_285956121.shtml

  3. http://www.360doc.com/content/12/1014/00/7471983_241330790.shtml

    http://www.360doc.com/content/12/1014/00/7471983_241330790.shtml

  4. http://www.360doc.com/content/10/1012/09/3722251_60285817.shtml

    http://www.360doc.com/content/10/1012/09/3722251_60285817.shtml http://www.docin.com/p-163063250.htm ...

  5. http://www.360doc.com/content/18/0406/16/15102180_743316618.shtml

    http://www.360doc.com/content/18/0406/16/15102180_743316618.shtml

  6. System.Thread.TImer控件——http://www.360doc.com/content/11/0812/11/1039473_139824496.shtml

    http://www.360doc.com/content/11/0812/11/1039473_139824496.shtml

  7. http://www.360doc.com/content/10/0928/12/11991_57014502.shtml

    http://www.360doc.com/content/10/0928/12/11991_57014502.shtml

  8. C++中的memset()函数 ------------转自:http://www.360doc.com/content/10/1006/18/1704901_58866679.shtml

    memset()函数可以对大内存的分配进行很方便的操作(初始化),所谓“初始化”,当然是指将你定义的变量或申请的空间赋予你所期望的值,例如语句int i=0;就表明定义了一个变量i,并初始化为0:如果 ...

  9. Maven运行JUnit测试(http://www.360doc.com/content/13/0927/15/7304817_317455642.shtml)

    Maven单元测试 分类: maven 2012-05-09 15:17 1986人阅读 评论(1) 收藏 举报 maven测试junit单元测试javarandom   目录(?)[-] maven ...

随机推荐

  1. Apache Common Math Stat

    http://commons.apache.org/proper/commons-math/userguide/stat.html mark   DescriptiveStatistics maint ...

  2. sql server创建临时表的两种写法和删除临时表

    --创建.删除临时表 --第一种方式 create table #tmp(name varchar(255),id int) --第二种方式 select count(id) as storyNum ...

  3. 20165336 2017-2018-2 《Java程序设计》第1周学习总结

    20165336 2017-2018-2 <Java程序设计>第1周学习总结 教材学习内容总结 Java地位.特点:Java具有面向对象.与平台无关.安全.稳定和多线程等优良特性.Java ...

  4. HashMap如何做循环遍历

    1.TestCase:

  5. Word Embedding理解

    一直以来感觉好多地方都吧Word Embedding和word2vec混起来一起说,所以导致对这俩的区别不是很清楚. 其实简单说来就是word embedding包含了word2vec,word2ve ...

  6. Too many connections解决方法

    在工作中,大家或许常常遇到Too many connections这个错误,这时作为DBA想进数据库管理都进不去,是非常尴尬的一件事情.当然有同学说可以修改配置文件,但是修改配置文件是需要重启mysq ...

  7. finecms栏目文章页seo设置

    finecms栏目页和文章页默认的标题是页面title_二级栏目title_一级栏目title_网站名称(比如:finecms怎么设置标题_finecms二次开发_finecms_ytkah博客),如 ...

  8. php程序猿面试分享

    面试总结 今天去了北京著名IT公司进行PHP程序猿的面试.这是人生第一次么,怎么不紧张?我是不是有病.不是.这叫自信呵. 首先是做一些笔试题. 1.mysql数据库索引使用的数据结构?这样做的优点是? ...

  9. entry.define编程思路

    0.lua将文字传给场景脚本. 1.场景脚本将pattern.define文件中的PAT当作子弹(水泡弹,带颜色) 2.用户的问题作为客户端的请求,发送给服务器端 3.服务器端接受客户端的问题请求 4 ...

  10. RN-android 打包后,部分图片不显示

    安卓打包后以及真机调试的时候部分图片不显示,原因是 安卓的包文件并不会每次都把图片资源重新打包.也就是说,你第一次打完包之后,再更新图片与代码,代码是会生效,但是图片文件是拿不到的,解决办法是 ../ ...