using System.ServiceModel.Web;//需要添加对该程序集的引用才能引用System.Runtime.Serialize.Json;
using System.Runtime.Serialization;//需要添加对该程序集的引用,才能使用DataContract,DataMember.
using System.Runtime.Serialization.Json;
public class JSONHelper
{
public static string Serialize<T>(T obj)//序列化为JSON
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)//反序列化为对象
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}
/// Our Person object to Serialize/Deserialize to JSON
[DataContract] //需引用System.Runtime.Serializable程序集
public class Person
{
public Person() { }
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
/// Sample code using the above helper methods
/// to serialize and deserialize the Person object
Person myPerson = new Person("Chris", "Pietschmann");
// Serialize
string json = JSONHelper.Serialize<Person>(myPerson);
// Deserialize
myPerson = JSONHelper.Deserialize<Person>(json);