如何使用 C 中的 Json.Net 将 JSON 数据反序列化为 Object

以下示例显示如何反序列化包含到 Object 中的 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

很少有事情需要注意

  1. 以下行将 json 字符串中数据的实际反序列化执行到 Employee 类的 employee 对象实例中。

Employee employee = JsonConvert.DeserializeObject<Employee>(json);

  1. 由于 employee.TitlesList<string> 类型,我们使用 foreach 循环结构来遍历 List 中的每个项目。