如何使用 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 使用缩进和新行序列化数据。如果不这样做,序列化字符串将是一个长字符串,没有缩进或换行符。