将Dictionary序列化为json数据 、json数据反序列化为Dictionary

需要引用System.Web.Extensions  dll类库

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

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;
}
上一篇:分布式Redis深度历险-Cluster


下一篇:putty如何使用