如何使用 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
很少有事情需要注意
- 以下行將 json 字串中資料的實際反序列化執行到
Employee
類的employee
物件例項中。
Employee employee = JsonConvert.DeserializeObject<Employee>(json);
- 由於
employee.Titles
是List<string>
型別,我們使用foreach
迴圈結構來遍歷List
中的每個專案。