码迷,mamicode.com
首页 > Windows程序 > 详细

C# Json数据反序列化为Dictionary并根据关键字获取指定值1

时间:2014-12-26 18:09:45      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

Json数据:

{
"dataSet": {
"header": {
"returnCode": "0",
"errorInfo": "HTTP请求错误",
"version": "V1.0R010",
"totalRows": "2000",
"returnRows": "20"
},
"fieldDefine": {
"assetId": "string",
"serverIdcId": "int",
"inputTime": "datetime"
},
"data": {
"row": [
{
"AssetId": "TCNS2006888",
"ServerIdcId": "1",
"InputTime": "2008-12-12"
},
{
"AssetId": "TCNS2006889",
"ServerIdcId": "2",
"InputTime": "2008-1-1"
}
]
}
}
}

问题:如何获取header中的数据行,以便显示在界面上?                                                 

效果图:                                

 

技术分享

将json数据转成dictionary的代码:

/// <summary>
/// 将json数据反序列化为Dictionary
/// </summary>
/// <param name="jsonData">json数据</param>
/// <returns></returns>
private Dictionary<string, object> JsonToDictionary(string jsonData)
{
//实例化JavaScriptSerializer类的新实例
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
//将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
return jss.Deserialize<Dictionary<string, object>>(jsonData);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

使用方法:

private void button1_Click(object sender, EventArgs e)
{
//Json数据
string json = "{\"dataSet\":{\"header\":{\"returnCode\":\"0\",\"errorInfo\":\"HTTP请求错误\",\"version\":\"V1.0R010\",\"totalRows\":\"2000\",\"returnRows\":\"20\"},\"fieldDefine\":{\"assetId\":\"string\",\"serverIdcId\":\"int\",\"inputTime\":\"datetime\"},\"data\":{\"row\":[{\"AssetId\":\"TCNS2006888\",\"ServerIdcId\":\"1\",\"InputTime\":\"2008-12-12\"},{\"AssetId\":\"TCNS2006889\",\"ServerIdcId\":\"2\",\"InputTime\":\"2008-1-1\"}]}}}";
Dictionary<string, object> dic = JsonToDictionary(json);//将Json数据转成dictionary格式
Dictionary<string, object> dataSet=(Dictionary<string, object>)dic["dataSet"];
//使用KeyValuePair遍历数据
foreach (KeyValuePair<string, object> item in dataSet)
{
if (item.Key.ToString() == "header")//获取header数据
{
var subItem=(Dictionary<string,object>)item.Value;
foreach (var str in subItem)
{
textBox1.AppendText(str.Key + ":" + str.Value+"\r\n");//显示到界面
}
break;
}
}
}

C# Json数据反序列化为Dictionary并根据关键字获取指定值1

标签:

原文地址:http://www.cnblogs.com/wangsai/p/4187067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!