Json的序列化和反序列化
时间:2011-06-16 来源:SirKevin
1、引用命名空间:
using System.Runtime.Serialization;
2、json的序列化和反序列化的方法:
public class JsonHelper
{
/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string 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>
public static 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]
public string Name { get; set; }
[DataMemberAttribute]
public int Age { get; set; }
[DataMemberAttribute]
public string Gender { get; set; }
}
4、现在就用JsonHelper方法把Person类的对象序列化成Json格式。
Person p = new Person { Name = "张三", Age = 12, Gender = "男" };
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);
7、结果:
张三,12,男
相关阅读 更多 +