C#在System.Web.Script.Serialization命名空间中提供了一个JavaScriptSerializer类,该类可实现JSON的序列化和反序列化。但该类有个小问题,就是关于DateTime类型数据的序列化问题,先看一段代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Person person = new Person()
{
Id = 1,
Name = "张三",
Gender = '男',
Age = 25,
Birthday = new DateTime(1995, 2, 14)
};
// 序列化JSON
string jsonText = A(person);
Console.WriteLine(jsonText);
// 反序列化JSON
B(jsonText);
Console.ReadKey(true);
}
static string A(Person person)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
return javaScriptSerializer.Serialize(person);
}
static void B(string jsonText)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
Person person = javaScriptSerializer.Deserialize<Person>(jsonText);
Console.WriteLine(person.Id);
Console.WriteLine(person.Name);
Console.WriteLine(person.Gender);
Console.WriteLine(person.Age);
Console.WriteLine(person.Birthday);
}
}
public class Person
{
/// <summary>
/// 编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public char Gender { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 生日
/// </summary>
public DateTime Birthday { get; set; }
}
}
运行结果如下,DateTime类型的数据比代码中定义的时间晚了8小时:
解决方案:利用JSON.NET实现序列化和反序列化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Person person = new Person()
{
Id = 1,
Name = "张三",
Gender = '男',
Age = 25,
Birthday = new DateTime(1995, 2, 14)
};
// 序列化JSON
string jsonText = A(person);
Console.WriteLine(jsonText);
// 反序列化JSON
B(jsonText);
Console.ReadKey(true);
}
static string A(Person person)
{
return JsonConvert.SerializeObject(person);
}
static void B(string jsonText)
{
Person person = JsonConvert.DeserializeObject<Person>(jsonText);
Console.WriteLine(person.Id);
Console.WriteLine(person.Name);
Console.WriteLine(person.Gender);
Console.WriteLine(person.Age);
Console.WriteLine(person.Birthday);
}
}
public class Person
{
/// <summary>
/// 编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public char Gender { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 生日
/// </summary>
public DateTime Birthday { get; set; }
}
}
运行结果如下图,结果正确