c#的webapi且net451 两层实体类转json
假设有以下两层实体类:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public List<Address> Addresses { get; set; }
}
public class Address
{
public string City { get; set; }
public string Street { get; set; }
}
使用Newtonsoft.Json库可以将实体类转换为JSON格式的字符串。
using Newtonsoft.Json;
// ...
User user = new User
{
Id = 1,
Name = "John",
Birthday = new DateTime(1990, 1, 1),
Addresses = new List<Address>
{
new Address { City = "New York", Street = "Broadway" },
new Address { City = "Los Angeles", Street = "Hollywood Blvd" }
}
};
string json = JsonConvert.SerializeObject(user);
Console.WriteLine(json);
输出结果:
{
"Id": 1,
"Name": "John",
"Birthday": "1990-01-01T00:00:00",
"Addresses": [
{
"City": "New York",
"Street": "Broadway"
},
{
"City": "Los Angeles",
"Street": "Hollywood Blvd"
}
]
}
原文地址: https://www.cveoy.top/t/topic/XUL 著作权归作者所有。请勿转载和采集!