在开发过程中,往往会遇到数据类型转换的情况,根据自己的业务,可能转换类型有多种,下面就说一下json字符串和字典类型的转换。
/// <summary>
/// 将字典类型序列化为json字符串
/// </summary>
/// <typeparam name="TKey">字典key</typeparam>
/// <typeparam name="TValue">字典value</typeparam>
/// <param name="dict">要序列化的字典数据</param>
/// <returns>json字符串</returns>
public static class JsonUntity
{
public static string SerializeDictionaryToJsonString<TKey, TValue>(Dictionary<TKey, TValue> dict)
{
if (dict.Count == 0)
return "";
string jsonStr = JsonConvert.SerializeObject(dict);
return jsonStr;
}
/// <summary>
/// 将json字符串反序列化为字典类型
/// </summary>
/// <typeparam name="TKey">字典key</typeparam>
/// <typeparam name="TValue">字典value</typeparam>
/// <param name="jsonStr">json字符串</param>
/// <returns>字典数据</returns>
public static Dictionary<TKey, TValue> DeserializeStringToDictionary<TKey, TValue>(string jsonStr)
{
if (string.IsNullOrEmpty(jsonStr))
return new Dictionary<TKey, TValue>();
Dictionary<TKey, TValue> jsonDict = JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(jsonStr);
return jsonDict;
}
}
List集合序列化可使用:
/// <summary>
/// JSON序列化
/// </summary>
public string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
C#:Json数据反序列化为Dictionary并根据关键字获取指定的值
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;
}
}
}