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;
}
}

3、现在预准备一个Person类:

class
Person
{
[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);

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,男

相关文章

网站地图xml地图