以下示例显示了如何反序列化包含在对象(即类的实例)中的JSON字符串。
using System; using System.Collections.Generic; using Newtonsoft.Json; public class Program { public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public bool IsManager { get; set; } public DateTime JoinedDate { get; set; } public IList<string> Titles { get; set; } } public static void Main() { string json = @"{ 'FirstName': 'Shiva', 'LastName': 'Kumar', 'IsManager': true, 'JoinedDate': '2014-02-10T00:00:00Z', 'Titles': [ 'Sr. Software Engineer', 'Applications Architect' ] }"; Employee employee = JsonConvert.DeserializeObject<Employee>(json); Console.WriteLine(employee.FirstName); Console.WriteLine(employee.LastName); Console.WriteLine(employee.JoinedDate); foreach (string title in employee.Titles) { Console.WriteLine(" {0}", title); } } }
如果运行此控制台程序,则各种Console.WriteLine语句的输出如下。
Shiva Kumar 2/10/2014 12:00:00 AM Sr. Software Engineer Applications Architect
几件事要注意
下一行将json字符串中的数据实际反序列化为该类的employee对象实例Employee。
Employee employee = JsonConvert.DeserializeObject<Employee>(json);
既然employee.Titles是一种List<string>类型,我们使用foreach循环构造来遍历那个中的每个项目List。