JSON 概览:
-
{ } - 对象
-
[ ] - 数组
-
"a": something - 财产
属性可以将对象、数组或值类型作为其值。例如:
{
"a": true,
"b": "hello",
"c": 5.2,
"d": 1,
"e": { "eChildProperty": "test" },
"f": [ "a", "b", "c" ]
}
让我们开始将这个 JSON 转录成类吧!
{
"contact":
{
"contact_type_ids": ["CUSTOMER"],
"name":"JSON Sample ResellerAVP",
"main_address":
{
"address_type_id":"ACCOUNTS",
"address_line_1":"Ayala Hills",
"city":"Muntinlupa",
"region":"NCR",
"postal_code":"1770",
"country_group_id":"ALL"
}
}
}
好的,所以我们有一个带有属性“contact”的根对象,它也是一个对象。让我们代表这两个:
public class RootObject
{
public Contact Contact { get; set; }
}
public class Contact
{
}
现在我们需要添加联系人的属性。它有3个:contact_type_ids是一个字符串数组,name是一个字符串,主地址是一个复杂对象。让我们代表那些:
public class Contact
{
[JsonProperty("contact_type_ids")]
public IList<string> ContactTypeIds { get; set; } // I'm using an IList, but any collection type or interface should work
public string Name { get; set; }
[JsonProperty("main_address")]
public Address MainAddress { get; set; }
}
public class Address
{
}
最后我们需要处理 Address 对象:
public class Address
{
[JsonProperty("address_type_id")]
public string AddressTypeId { get; set; }
[JsonProperty("address_line_1")]
public string AddressLine1 { get; set; }
public string City { get; set; }
public string Region { get; set; }
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
[JsonProperty("country_group_id")]
public string CountryGroupId { get; set; }
}
把这一切放在一起,我们得到:
public class RootObject
{
public Contact Contact { get; set; }
}
public class Contact
{
[JsonProperty("contact_type_ids")]
public IList<string> ContactTypeIds { get; set; } // I'm using an IList, but any collection type or interface should work
public string Name { get; set; }
[JsonProperty("main_address")]
public Address MainAddress { get; set; }
}
public class Address
{
[JsonProperty("address_type_id")]
public string AddressTypeId { get; set; }
[JsonProperty("address_line_1")]
public string AddressLine1 { get; set; }
public string City { get; set; }
public string Region { get; set; }
[JsonProperty("postal_code")]
public string PostalCode { get; set; }
[JsonProperty("country_group_id")]
public string CountryGroupId { get; set; }
}
我们可以这样使用它:
RootObject deserialized = JsonConvert.DeserializeObject<RootObject>(jsonString);
Try it online
JSON 并不复杂。只需查看您拥有的数据即可理解并手动转换为类非常简单。