1、引用命名空间:
using System.Runtime.Serialization;
2、json的序列化和反序列化的方法:
publicclass JsonHelper
{
///<summary>
/// 序列化
///</summary>
///<typeparam name="T"></typeparam>
///<param name="t"></param>
///<returns></returns>
publicstaticstring JsonSerializer<T>(T t)
{
string jsonString =string.Empty;
DataContractJsonSerializer ser =new DataContractJsonSerializer(typeof(T));
MemoryStream ms =new MemoryStream();
ser.WriteObject(ms, t);
jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
///<summary>
/// 反序列化
///</summary>
///<typeparam name="T"></typeparam>
///<param name="jsonString"></param>
///<returns></returns>
publicstatic T JsonDeserialize<T>(string jsonString)
{
T obj =default(T);
DataContractJsonSerializer ser=new DataContractJsonSerializer(typeof(T));
MemoryStream ms =new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
obj = (T)ser.ReadObject(ms);
return obj;
}
}
{
///<summary>
/// 序列化
///</summary>
///<typeparam name="T"></typeparam>
///<param name="t"></param>
///<returns></returns>
publicstaticstring JsonSerializer<T>(T t)
{
string jsonString =string.Empty;
DataContractJsonSerializer ser =new DataContractJsonSerializer(typeof(T));
MemoryStream ms =new MemoryStream();
ser.WriteObject(ms, t);
jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
///<summary>
/// 反序列化
///</summary>
///<typeparam name="T"></typeparam>
///<param name="jsonString"></param>
///<returns></returns>
publicstatic T JsonDeserialize<T>(string jsonString)
{
T obj =default(T);
DataContractJsonSerializer ser=new DataContractJsonSerializer(typeof(T));
MemoryStream ms =new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
obj = (T)ser.ReadObject(ms);
return obj;
}
}
3、现在先准备一个Person类:
class Person
{
[DataMemberAttribute]
publicstring Name { get; set; }
[DataMemberAttribute]
publicint Age { get; set; }
[DataMemberAttribute]
publicstring Gender { get; set; }
}
{
[DataMemberAttribute]
publicstring Name { get; set; }
[DataMemberAttribute]
publicint Age { get; set; }
[DataMemberAttribute]
publicstring Gender { get; set; }
}
4、现在就用JsonHelper方法把Person类的对象序列化成Json格式。
Person p =new Person { Name ="张三", Age =12, Gender ="男" };
string str = JsonHelper.JsonSerializer<Person>(p);
Console.WriteLine(str);
string str = JsonHelper.JsonSerializer<Person>(p);
Console.WriteLine(str);
5、结果:
{"Age":12,"Gender":"男","Name":"张三"}
6、再把Json格式反序列化为Person类型:
p = JsonHelper.JsonDeserialize<Person>(str);
Console.WriteLine("{0},{1},{2}",p.Name,p.Age,p.Gender);
Console.WriteLine("{0},{1},{2}",p.Name,p.Age,p.Gender);
7、结果:
张三,12,男