总结一下C#操作json的两种方式,都是将对象和json格式相转。

1.JavaScriptSerializer,继承自System.Web.Script.Serialization

private string Serializer<T>(T t)
{
JavaScriptSerializer json=new JavaScriptSerializer();
return json.Serialize(t);
} private T DeSerialze<T>(string strJeson) {
JavaScriptSerializer strJeson1 = new JavaScriptSerializer();
return strJeson1.Deserialize<T>(strJeson);
}

2.DataContractJsonSerializer,继承自System.Runtime.Serialization.Json;

代码如下
/// <summary>
/// create json data according to entity
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string GetJsonSerializar<T>(T t)
{
var ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms=new MemoryStream())
{
ser.WriteObject(ms,t);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// parse json data accroding to json string data
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonStr"></param>
/// <returns></returns>
public static T ParseFromJson<T>(string jsonStr)
{
//T obj = Activator.CreateInstance<T>();
//using (MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
//{
// DataContractJsonSerializer jsonSerializer=new DataContractJsonSerializer(obj.GetType());
// return (T) jsonSerializer.ReadObject(ms);
//}
var ser = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
var obj = (T)ser.ReadObject(ms);
return obj;
}

但是json在客户端和浏览器传递之间时,如果传递的是实体类的json格式数据,则这类实体类应该用协议去定义,例如:

[DataContract]
public class MsgEntity
{
[DataMember(Order = ,IsRequired = true)]
public string Msg { get; set; } [DataMember(Order = , IsRequired = false)]
public string HtmlMsg { get; set; }
}
04-30 10:44