1) 首先去http://json.codeplex.com/ 下载Newtonsoft.Json这个Reference DLL。
2)新建一个项目后引用上面所下载对应版本的DLL。
3) 项目中使用的源代码如下:这里通过使用JsonConvert类来实现对JSON的序列化与反序列化。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Person> listPerson = new List<Person>();
Person person = null;
for (int i = 0; i < 10; i++)
{
person = new Person();
person.Name = string.Format("xxxx{0}", i);
person.Age = 20 + i;
person.Birthday = DateTime.Now.AddDays(i);
person.Sex = i % 2 == 0 ? "女" : "男";
listPerson.Add(person);
}
//把对象序列化成JSON字符串
string serialStr = JsonConvert.SerializeObject(listPerson);
Console.WriteLine(serialStr);
//把JSON字符串反序列化成对象
List<Person> list = new List<Person>();
list = JsonConvert.DeserializeObject<List<Person>>(serialStr);
Console.Read();
}
}
public class Person
{
public string Name
{ get; set; }
public int Age { get; set; }
public string Sex { get; set; }
public DateTime Birthday { get; set; }
}
}