JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。
关于内存对象和JSON字符串的相互转换,在实际项目中应比较广泛,经过一番搜索,找到如下三种方法来解决此问题,分别是使用 Newtonsoft.Json.dll、DataContractJsonSerializer、 JavaScriptSerializer。
方法一: Newtonsoft.Json.dll
Newtonsoft.Json.dll在.net2.0之后的版本可以支持 我的版本.net framework4.0
类设计:
class JsonNewtonsoft
{
/// <summary>
/// 把对象转换为JSON字符串
/// </summary>
/// <param name="o">对象</param>
/// <returns>JSON字符串</returns>
public static string ToJSON(this object o)
{
if (o == null)
{
return null;
}
return JsonConvert.SerializeObject(o);
}
/// <summary>
/// 把Json文本转为实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="input"></param>
/// <returns></returns>
public static T FromJSON<T>(this string input)
{
try
{
return JsonConvert.DeserializeObject<T>(input);
}
catch (Exception ex)
{
return default(T);
}
}
}
方法二:DataContractJsonSerializer
使用这种 需要引用 System.Runtime.Serialization.dll
类设计:
class JsonDataContractJsonSerializer
{
/// <summary>
/// 内存对象转换为json字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ObjectToJson(object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, obj);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
return Encoding.UTF8.GetString(dataBytes);
}
/// <summary>
/// Json字符串转内存对象
/// </summary>
/// <param name="jsonString"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static object JsonToObject(string jsonString, object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
return serializer.ReadObject(mStream);
}
}
方法三:JavaScriptSerializer
需要引用:System.Web.Extensions.dll
类设计:
public static class JsonJavaScriptSerializer
{
/// <summary>
/// 内存对象转换为json字符串
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJSON(object obj)
{
StringBuilder sb = new StringBuilder();
JavaScriptSerializer json = new JavaScriptSerializer();
json.Serialize(obj, sb);
return sb.ToString();
}
/// <summary>
/// Json字符串转内存对象
/// </summary>
/// <param name="jsonString"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static T FromJSON<T>(string jsonString)
{
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Deserialize<T>(jsonString);
}
}