一:使用JavaScriptSerializer
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("id", "1");
dic.Add("name", "jition");
var serializer = new JavaScriptSerializer();
//将object对象转换为字符
var json = serializer.Serialize(dic);
//将json字符转换为object对象
var obj = serializer.Deserialize<Dictionary<string, string>>(json);
二:使用封装方法(DataContractJsonSerializer)
/// <summary>
/// 将C#数据实体转化为JSON数据
/// </summary>
/// <param name="obj">要转化的数据实体</param>
/// <returns>JSON格式字符串</returns>
public static string JsonSerialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, obj);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string resultStr = sr.ReadToEnd();
sr.Close();
stream.Close();
return resultStr;
}
/// <summary>
/// 将JSON数据转化为C#数据实体
/// </summary>
/// <param name="json">符合JSON格式的字符串</param>
/// <returns>T类型的对象</returns>
public static T JsonDeserialize<T>(string json)
{
//json 必须为 {name:"value",name:"value"} 的格式(要符合JSON格式要求)
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json.ToCharArray()));
T obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}