c# - 具有数组结构的 JSON
问题描述
我只想问是否如何在 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"
}
}
}
解决方案
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);
JSON 并不复杂。只需查看您拥有的数据,就可以轻松理解并手动转换为类。
推荐阅读
- c - 将项目添加到数据结构 (C)
- angular - PrimeNG 在单个选择中从表中删除行选择
- visual-studio - CSV 上的 SSIS SSMS 逗号问题
- python - Python Pandas 将列表中的多个 SAS 文件读取到单独的数据帧中
- javascript - 显示带有动态数据的高图
- python - 在 django 中从用户输入写入 csv 文件:每个字符出现在新行上
- macos - GCC 未检测到 MacOS Mojave 中的库路径
- ios - Swift:线程 1:EXC_BAD_ACCESS 即使有警卫
- php - PHP 生成的 HTML 的备用背景底纹的
- python - tkinter 中的 bind 和 master.bind 有什么区别?