1.DataContractJsonSerializer
DataContractJsonSerializer在System.Runtime.Serialization.Json命名空间下,.NETFramework 3.5包含在System.ServiceModel.Web.dll中,需要添加对其的引用;.NETFramework 4在System.Runtime.Serialization中
序列化对象示例:
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
/// <summary>
/// 涉及时间转换问题
/// </summary>
public DateTime BirthDay { get; set; }
/// <summary>
/// Dictionary
/// </summary>
public Dictionary<string, int> Subjects { get; set; }
public Address Adress { get; set; }
/// <summary>
/// 集合类型
/// </summary>
public List<Role> RoleList { get; set; }
/// <summary>
/// 枚举接口
/// </summary>
public IEnumerable<Department> Departments { get; set; }
/// <summary>
/// 数组问题
/// </summary>
public string[] favoriteFruit { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Address
{
public string Province { get; set; }
public string City { get; set; }
public string District { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
简单封装下DataContractSerializer,如下:
public static class JsonHelper
{
public static T DeserializeFromString<T>(string str) where T : class
{
try
{
byte[] buffer = Encoding.UTF8.GetBytes(str);
MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
return ser.ReadObject(ms) as T;
}
catch (Exception e)
{
return null;
}
}
public static string SerializeToString<T>(T t) where T : class
{
try
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
string result = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
ser.WriteObject(ms, t);
result = Encoding.UTF8.GetString(ms.ToArray());
}
return result;
}
catch
{
return null;
}
}
}
序列化代码如下:
Person p = new Person();
p.Adress = new Address
{
Province = "江西",
City = "九江",
District = "D1"
};
p.Age = 20;
p.Name = "张三";
p.BirthDay = DateTime.Parse("1990-09-09 09:00:00");
p.Subjects = new Dictionary<string, int> { { "java", 99 }, { ".net", 100 } };
p.RoleList = new List<Role>() { new Role() { Id = 1, Name = "Role1" }, new Role { Id = 2, Name = "Role2" } };
p.favoriteFruit = new string[] { "apple",