1、引用命名空间:
2、json的序列化和反序列化的方法:
{
///
/// 序列化
///
///
///
///
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;
}
///
/// 反序列化
///
///
///
///
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类:
{
[DataMemberAttribute]
publicstring Name { get; set; }
[DataMemberAttribute]
publicint Age { get; set; }
[DataMemberAttribute]
publicstring Gender { get; set; }
}
4、现在就用JsonHelper方法把Person类的对象序列化成Json格式。
string str = JsonHelper.JsonSerializer<Person>(p);
Console.WriteLine(str);
5、结果:
6、再把Json格式反序列化为Person类型:
Console.WriteLine("{0},{1},{2}",p.Name,p.Age,p.Gender);
7、结果: