在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(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库处理复杂对象。