如何利用.Net内置类,解析未知复杂Json对象
如果你乐意,当然可以使用强大的第三方类库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;
}
}
}
}

如何利用.Net内置类,解析未知复杂Json对象的更多相关文章
- 【Android】18.1 利用安卓内置的定位服务实现位置跟踪
分类:C#.Android.VS2015: 创建日期:2016-03-04 一.安卓内置的定位服务简介 通常将各种不同的定位技术称为位置服务或定位服务.这种服务是通过电信运营商的无线电通信网络(如GS ...
- SQL Server利用RowNumber()内置函数与Over关键字实现通用分页存储过程(支持单表或多表结查集分页)
SQL Server利用RowNumber()内置函数与Over关键字实现通用分页存储过程,支持单表或多表结查集分页,存储过程如下: /******************/ --Author:梦在旅 ...
- EXT心得--并非所有的items配置对象都属于EXT的内置类
之前我对EXT的items中未指明xtype的配置对象有一个错误的认识--即虽然某个items未指明它下面的某个组件的xtype,但这个组件肯定属性EXT的某个类.然而今天在查看actioncolum ...
- Python继承扩展内置类
继承最有趣的应用是给内置类添加功能,在之前的Contact类中,我们将联系人添加到所有联系人的列表里,如果想通过名字来搜索,那么就可以在Contact类添加一个方法用于搜索,但是这种方法实际上属于列表 ...
- Python内置类属性,元类研究
Python内置类属性 我觉得一切都是对象,对象和元类对象,类对象其实都是一样的,我在最后进行了证明,但是只能证明一半,最后由于元类的父类是type,他可以阻挡对object属性的访问,告终 __di ...
- python 练习题:请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串
# -*- coding: utf-8 -*- # 请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串 n1 = 255 n2 = 1000 print(hex(n1)) pr ...
- 利用Windows内置工具winsat测试硬盘速度(SSD&机械盘对比)
利用Windows内置工具winsat测试硬盘速度(SSD&机械盘对比) 以下是红色内容是在命令行运行: C:\Users\Administrator>winsat diskWindow ...
- Python内置类属性
__dict__ : 类的属性(包含一个字典,由类的数据属性组成) __doc__ :类的文档字符串 __name__: 类名 __module__: 类定义所在的模块(类的全名是'__main__. ...
- 利用Java内置的API开发JMX功能
一.什么是JMX JMS是一种Java规范,定义了如何管理一个软件系统(或应用程序)的规范. 对于一个简单的应用程序,该程序本身不需要被管理.但如果是开发的一个复杂系统(如一个电商平台.一个企业内部管 ...
随机推荐
- iWatch # 初始化工程
iWatch --利用swift,开发iWatch手表小应用! 远程仓库,团队开发: $ git init $ git add . $ git commit -m “ProjectName” // p ...
- order by使用方法
1.ORDER BY 中关于NULL的处理 缺省处理,Oracle在Order by 时觉得null是最大值,所以假设是ASC升序则排在最后,DESC降序则排在最前. 当然,你也能够使用nulls f ...
- 在面对变化,撇开NO
参观后转到供应商,看到自己的生产线流水线半自己的钣金生产线举措.这就是我一直想厂提高生产现场的想法,因为通常当我看到工作人员努力工作和繁忙的生产,只见废现场,线解决方式时,有点莫名的兴奋. 幸亏是一家 ...
- [Oracle] Insert All神奇
无条件插入 Oracle中间insert all它指的是相同的数据组成不同的表.如果有需求现在:该t插入数据表t1,t2,假设你不知道insert all.您可以使用insert插入2次要,例如,见下 ...
- 深入struts2.0(五)--Dispatcher类
1.1.1 serviceAction方法 在上个Filter方法中我们会看到例如以下代码: this.execute.executeAction(request, response, m ...
- 使用WebBrowser控件时在网页元素上绘制文本或其他自定义内容
原文:使用WebBrowser控件时在网页元素上绘制文本或其他自定义内容 第一次在CNBlogs上发Post是提出一个有关使用WebBrowser控件时对SELECT网页元素操作的疑惑,这个问题至今也 ...
- linux 内核睡眠与唤醒
休眠(被阻塞)的进程处于一个特殊的不可执行状态.进程休眠由多种原因,但肯定都是为了等待一些事件.事件可能是一 段时间从文件I/O读取更多数据,或者是某个硬件事件.一个进程还由可能在尝试获取一个已被占用 ...
- vSphere HA状况:未知配置错误解决的方法
问题:vSphere HA配置出现未知错误,导致打不开主机上的虚拟机电源,vmware client连接vcenter后,主机显示警报信息,例如以下: 解决:例如以下图,选中有问题的物理主机,然后又一 ...
- 随记一个C的时间加减
//Centos6 x86_64 #include <time.h>#include <stdio.h>#include <string.h>#include &l ...
- Delta3D 2.8版本号 预习
http://blog.csdn.net/zhuyingqingfen/article/details/38581453 看到官网今天的更新.发现即将公布的delta3d 2.8 版本号 做了非常大的 ...