在C#中,使用Newtonsoft.Json庫處理復雜對象非常簡單。首先,確保已經安裝了Newtonsoft.Json NuGet包。然后,按照以下步驟操作:
Employee
類:public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
Newtonsoft.Json
庫將對象序列化為JSON字符串:using Newtonsoft.Json;
Employee employee = new Employee
{
Id = 1,
Name = "John Doe",
Address = new Address
{
Street = "123 Main St",
City = "Anytown",
State = "CA",
ZipCode = "12345"
}
};
string jsonString = JsonConvert.SerializeObject(employee);
Console.WriteLine(jsonString);
這將輸出以下JSON字符串:
{"Id":1,"Name":"John Doe","Address":{"Street":"123 Main St","City":"Anytown","State":"CA","ZipCode":"12345"}}
Newtonsoft.Json
庫將JSON字符串反序列化為復雜對象:string jsonString = "{\"Id\":1,\"Name\":\"John Doe\",\"Address\":{\"Street\":\"123 Main St\",\"City\":\"Anytown\",\"State\":\"CA\",\"ZipCode\":\"12345\"}}";
Employee employee = JsonConvert.DeserializeObject<Employee>(jsonString);
Console.WriteLine($"Id: {employee.Id}, Name: {employee.Name}, Address: {employee.Address.Street}, {employee.Address.City}, {employee.Address.State}, {employee.Address.ZipCode}");
這將輸出:
Id: 1, Name: John Doe, Address: 123 Main St, Anytown, CA, 12345
通過這些步驟,您可以在C#中使用Newtonsoft.Json庫處理復雜對象。