如何利用.Net内置类,解析未知复杂Json对象_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 如何利用.Net内置类,解析未知复杂Json对象

如何利用.Net内置类,解析未知复杂Json对象

 2013/8/28 10:55:35  三聪  博客园  我要评论(0)
  • 摘要:如果你乐意,当然可以使用强大的第三方类库Json.Net中的JObject类解析复杂Json字串。我不太希望引入第三方类库,所以在.Net内置类JavaScriptSerializer.DeserializeObject的基础上做了一些封装,可以方便的读取复杂json中的内容,而无需专门定义对应的类型。等不及看的,直接下载源码:JsonObject.7z代码实例:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq
  • 标签:.net net 未知 利用 JSON 解析 JS

如果你乐意,当然可以使用强大的第三方类库Json.Net中的JObject类解析复杂Json字串 。

我不太希望引入第三方类库,所以在.Net内置类JavaScriptSerializer.DeserializeObject的基础上做了一些封装,可以方便的读取复杂json中的内容,而无需专门定义对应的类型。

等不及看的,直接下载源码: JsonObject.7z

 

代码实例:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace JsonUtils
{
    class Program
    {
        static void Main(string[] args)
        {
            WebClient client = new WebClient();
            string json = @"{""errNo"":""0"", data : { ""31"": { ""content"": { ""week"": ""周三"" , ""city"": ""上海"" , ""today"": { ""condition"": ""多云"" , ""temp"": ""35~28℃"" , ""wind"": ""南风3-4级"" , ""imgs"": [ ""a1"" , ""a1"" ] , ""img"": [ ""http:\/\/open.baidu.com\/stat\/weather\/newday\/01.gif"" , ""http:\/\/open.baidu.com\/stat\/weather\/newnight\/01.gif"" ] , ""link"": ""http:\/\/www.weather.com.cn\/html\/weather\/101020100.shtml"" , ""pm25"": ""76"" , ""pollution"": ""10"" , ""pm25url"": ""http:\/\/www.baidu.com\/s?wd=%E4%B8%8A%E6%B5%B7%E7%A9%BA%E6%B0%94%E8%B4%A8%E9%87%8F%E6%8C%87%E6%95%B0"" , ""pmdate"": false } , ""tomorrow"": { ""condition"": ""多云转阵雨"" , ""temp"": ""36~27℃"" , ""wind"": ""南风3-4级"" , ""imgs"": [ ""a1"" , ""a1"" ] , ""img"": [ ""http:\/\/open.baidu.com\/stat\/weather\/newday\/01.gif"" , """" ] , ""link"": ""http:\/\/www.weather.com.cn\/html\/weather\/101020100.shtml"" , ""pm25"": ""76"" , ""pollution"": ""10"" , ""pm25url"": ""http:\/\/www.baidu.com\/s?wd=%E4%B8%8A%E6%B5%B7%E7%A9%BA%E6%B0%94%E8%B4%A8%E9%87%8F%E6%8C%87%E6%95%B0"" , ""pmdate"": false } , ""thirdday"": { ""condition"": ""阵雨转阴"" , ""temp"": ""32~24℃"" , ""wind"": ""北风3-4级"" , ""imgs"": [ ""a3"" , ""a1"" ] , ""img"": [ ""http:\/\/open.baidu.com\/stat\/weather\/newday\/03.gif"" , """" ] , ""link"": ""http:\/\/www.weather.com.cn\/html\/weather\/101020100.shtml"" , ""pm25"": ""76"" , ""pollution"": ""10"" , ""pm25url"": ""http:\/\/www.baidu.com\/s?wd=%E4%B8%8A%E6%B5%B7%E7%A9%BA%E6%B0%94%E8%B4%A8%E9%87%8F%E6%8C%87%E6%95%B0"" , ""pmdate"": false } , ""linkseven"": ""http:\/\/www.weather.com.cn\/html\/weather\/101020100.shtml#7d"" , ""source"": { ""name"": ""中国气象频道"" , ""url"": ""http:\/\/www.mywtv.cn\/"" } , ""cityname"": ""上海"" , ""ipcity"": ""上海"" , ""ipprovince"": ""上海"" , ""isauto"": true } , ""setting"": ""自动"" } } }";

            JsonObject value = JsonObject.Parse(json);

            Console.Write(value["data"]["31"]["content"]["thirdday"]["img"][0].Text());
            Console.Read();
            
        }
    }
}

 

封装的类:

/*
* Copyright (C) 2013 cnblogs.com All Rights Reserved 
*
* Description : Json字串解析成字典
* Auther      : gateluck
* CreateDate  : 2013-08-27
* History     : 
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;

namespace JsonUtils
{
    public class JsonObject
    {
        /// <summary>
        /// 解析JSON字串
        /// </summary>
        public static JsonObject Parse(string json)
        {
            var js = new JavaScriptSerializer();

            object obj = js.DeserializeObject(json);

            return Cast(obj);
        }

        /// <summary>
        /// 将普通字典类型转为JsonObject
        /// </summary>
        private static JsonObject Cast(object value)
        {
            var obj = new JsonObject();

            //如果是数组
            if (value is object[])
            {

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

                object[] array = (object[])value;
                for (int i = 0; i < array.Length; i++)
                {
                    list.Add(Cast(array[i]));
                }
                obj.Value = list.ToArray();
            }
            //如果是字典
            else if (value is Dictionary<string, object>)
            {
                var dict = value as Dictionary<string, object>;
                var dict2 = new Dictionary<string, JsonObject>();
                foreach (var entry in dict)
                {
                    dict2.Add(entry.Key, Cast(entry.Value));
                }
                obj.Value = dict2;
            }
            //如果是普通类
            else
            {
                obj.Value = value;
            }
            return obj;
        }

        /// <summary>
        /// 取对象的属性
        /// </summary>
        public JsonObject this[string key]
        {
            get
            {
                var dict = this.Value as Dictionary<string, JsonObject>;
                if (dict != null && dict.ContainsKey(key))
                {
                    return dict[key];
                }

                return new JsonObject();
            }

        }
        /// <summary>
        /// 取数组
        /// </summary>
        public JsonObject this[int index]
        {
            get
            {
                var array = this.Value as JsonObject[];
                if (array != null && array.Length > index)
                {
                    return array[index];
                }
                return new JsonObject();
            }

        }

        /// <summary>
        /// 将值以希望类型取出
        /// </summary>
        public T GetValue<T>()
        {
            return (T)Convert.ChangeType(Value, typeof(T));
        }

        /// <summary>
        /// 取出字串类型的值
        /// </summary>
        public string Text()
        {
            return Convert.ToString(Value);
        }

        /// <summary>
        /// 取出数值
        /// </summary>
        public double Number()
        {
            return Convert.ToDouble(Value);
        }

        /// <summary>
        /// 取出整型
        /// </summary>
        public int Integer()
        {
            return Convert.ToInt32(Value);
        }

        /// <summary>
        /// 取出布尔型
        /// </summary>
        public bool Boolean()
        {
            return Convert.ToBoolean(Value);
        }


        /// <summary>
        ////// </summary>
        public object Value
        {
            get;
            private set;
        }

        /// <summary>
        /// 如果是数组返回数组长度
        /// </summary>
        public int Length
        {
            get
            {
                var array = this.Value as JsonObject[];
                if (array != null)
                {
                    return array.Length;
                }
                return 0;
            }
        }
    }
}

 

 

发表评论
用户名: 匿名