如何使用 C 中的 Json.Net 將物件序列化為 JSON
以下示例顯示如何使用 Json.Net 將 C#Object 例項中的資料序列化為 JSON 字串。
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
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 class Program
{
public static void Main()
{
Employee employee = new Employee
{
FirstName = "Shiva",
LastName = "Kumar",
IsManager = true,
JoinedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Titles = new List<string>
{
"Sr. Software Engineer",
"Applications Architect"
}
};
string json = JsonConvert.SerializeObject(employee, Formatting.Indented);
Console.WriteLine(json);
}
}
如果你執行這個控制檯程式,Console.WriteLine(json)
的輸出將是
{
"FirstName": "Shiva",
"LastName": "Kumar",
"IsManager": true,
"JoinedDate": "2013-01-20T00:00:00Z",
"Titles": [
"Sr. Software Engineer",
"Applications Architect"
]
}
很少有事情需要注意
-
以下行將
employee
類例項內的資料實際序列化為 json 字串string json = JsonConvert.SerializeObject(employee, Formatting.Indented);
-
引數
Formatting.Indented
告訴 Json.Net 使用縮排和新行序列化資料。如果不這樣做,序列化字串將是一個長字串,沒有縮排或換行符。