我正在使用返回
JSON数据的Web服务,并且在很多情况下,服务会在一个对象中返回几个属性,我想将它们分组到C#端的类中.考虑一个类结构,如:
class Person
{
public Address Address { get; set; }
public string Name { get; set; }
}
class Address
{
public string StreetAddress { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
}
和JSON数据如:
{ "Name" : "Pilchie",
"StreetAddress" : "1234 Random St",
"City" : "Nowheretown",
"Zip" : "12345"
}
是否可以将我的Person和Address类属性化,以便它们序列化/反序列化为这种格式?
最佳答案 我不认为你可以让JSON.NET一次性完成这一切 – 你必须手动创建Person对象.但是,您可以在不创建单独的DTO类的情况下完成此操作.例如:
var jsonText = "{ \"Name\" : \"Pilchie\"," +
"\"StreetAddress\" : \"1234 Random St\"," +
"\"City\" : \"Nowheretown\"," +
"\"Zip\" : \"12345\"" +
"}";
JObject jsonObject = (JObject) JsonConvert.DeserializeObject(jsonText);
var person =
new Person
{
Address = new Address
{
City = (String) jsonObject["City"],
StreetAddress = (String) jsonObject["StreetAddress"],
ZipCode = (string) jsonObject["Zip"]
},
Name = (string) jsonObject["Name"]
};
并序列化:
JsonConvert.SerializeObject(
new
{
person.Name,
person.Address.StreetAddress,
person.Address.City,
Zip = person.Address.ZipCode
});