作者:快乐碧云轩在江湖 | 来源:互联网 | 2023-02-01 19:54
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的代码:
///
/// 将json数据反序列化为Dictionary
///
///
json数据
///
private Dictionary
JsonToDictionary(string jsonData)
{
//实例化JavascriptSerializer类的新实例
JavascriptSerializer jss = new JavascriptSerializer();
try
{
//将指定的 JSON 字符串转换为 Dictionary 类型的对象
return jss.Deserialize>(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 dic = JsonToDictionary(json);//将Json数据转成dictionary格式
Dictionary dataSet=(Dictionary)dic["dataSet"];
//使用KeyValuePair遍历数据
foreach (KeyValuePair item in dataSet)
{
if (item.Key.ToString() == "header")//获取header数据
{
var subItem=(Dictionary)item.Value;
foreach (var str in subItem)
{
textBox1.AppendText(str.Key + ":" + str.Value+"\r\n");//显示到界面
}
break;
}
}
}
C# Json数据反序列化为Dictionary并根据关键字获取指定值1