如何利用.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对象的更多相关文章

  1. 【Android】18.1 利用安卓内置的定位服务实现位置跟踪

    分类:C#.Android.VS2015: 创建日期:2016-03-04 一.安卓内置的定位服务简介 通常将各种不同的定位技术称为位置服务或定位服务.这种服务是通过电信运营商的无线电通信网络(如GS ...

  2. SQL Server利用RowNumber()内置函数与Over关键字实现通用分页存储过程(支持单表或多表结查集分页)

    SQL Server利用RowNumber()内置函数与Over关键字实现通用分页存储过程,支持单表或多表结查集分页,存储过程如下: /******************/ --Author:梦在旅 ...

  3. EXT心得--并非所有的items配置对象都属于EXT的内置类

    之前我对EXT的items中未指明xtype的配置对象有一个错误的认识--即虽然某个items未指明它下面的某个组件的xtype,但这个组件肯定属性EXT的某个类.然而今天在查看actioncolum ...

  4. Python继承扩展内置类

    继承最有趣的应用是给内置类添加功能,在之前的Contact类中,我们将联系人添加到所有联系人的列表里,如果想通过名字来搜索,那么就可以在Contact类添加一个方法用于搜索,但是这种方法实际上属于列表 ...

  5. Python内置类属性,元类研究

    Python内置类属性 我觉得一切都是对象,对象和元类对象,类对象其实都是一样的,我在最后进行了证明,但是只能证明一半,最后由于元类的父类是type,他可以阻挡对object属性的访问,告终 __di ...

  6. python 练习题:请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串

    # -*- coding: utf-8 -*- # 请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串 n1 = 255 n2 = 1000 print(hex(n1)) pr ...

  7. 利用Windows内置工具winsat测试硬盘速度(SSD&机械盘对比)

    利用Windows内置工具winsat测试硬盘速度(SSD&机械盘对比) 以下是红色内容是在命令行运行: C:\Users\Administrator>winsat diskWindow ...

  8. Python内置类属性

    __dict__ : 类的属性(包含一个字典,由类的数据属性组成) __doc__ :类的文档字符串 __name__: 类名 __module__: 类定义所在的模块(类的全名是'__main__. ...

  9. 利用Java内置的API开发JMX功能

    一.什么是JMX JMS是一种Java规范,定义了如何管理一个软件系统(或应用程序)的规范. 对于一个简单的应用程序,该程序本身不需要被管理.但如果是开发的一个复杂系统(如一个电商平台.一个企业内部管 ...

随机推荐

  1. UVA 10139 Factovisors(数论)

    Factovisors The factorial function, n! is defined thus for n a non-negative integer: 0! = 1 n! = n * ...

  2. Oracle 免费的数据库

    Oracle 免费的数据库--Database 快捷版 11g 安装使用与"SOD框架"对Oracle的CodeFirst支持 一.Oracle XE 数据库与连接工具安装使用 O ...

  3. css2与css3的区别

    css2与css3的区别 CSS3引进了一些新的元素新的特性,我收集以下,自己做了一个小结: animation(基础动画)eg:  div{animation: myfirst 5s linear ...

  4. [LeetCode]Copy List with Random Pointer &amp;Clone Graph 复杂链表的复制&amp;图的复制

    /** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label ...

  5. Android KeyStore Stack Buffer Overflow (CVE-2014-3100)

    /* 本文章由 莫灰灰 编写,转载请注明出处. 作者:莫灰灰    邮箱: minzhenfei@163.com */ 1. KeyStore Service 在Android中,/system/bi ...

  6. 退出手机QQ依旧显示在线

    老婆说明明看到你手机QQ在线,怎么发信息不回复?这让我非常是冤枉,我明明退出了啊! 晚上宝宝睡觉后,我们一起来研究,发现了当中的秘密,原来仅仅要选择了"退出后仍接受消息通知"这个选 ...

  7. php rsa 加密、解密、签名、验签

    由于对接第三方机构使用的是Java版本的rsa加解密方法,所有刚开始在网上搜到很多PHP版本的rsa加解密,但是对接java大多都不适用. 以下php版本是适用于对接java接口,java适用密钥再p ...

  8. Gimp教程:多图层多渐变的文字效果

    这个教程是我在国外的视频网站上学的,制作这个教程也很久了,今天在网盘翻看到这个截图版本,正好整理到博客,方便管理.记得当时花了一下午的时间来边做边截图修改制作,个人觉得这个教程还是很好的,原作者很有创 ...

  9. Linux下的C程序如何调用系统命令,并获取系统的输出信息到C程序中

    直接贴代码: #include <stdio.h> #include <string.h> #include <errno.h> int main(int argc ...

  10. leetcode[60] Rotate List

    题目:给定链表,和一个k,把链表的后k个旋转到前头,例如链表为: 1->2->3->4->5->NULL and k = 2, return 4->5->1- ...