c# - 创建复杂的多个动态对象以创建嵌套的 json
问题描述
创建 json 的新手,但需要准备一些数据发送到 API,所以有时间学习。
这就是我想要创造的;
[
{
"alias": "H02010",
"address": "Demoroad 9",
"city": "Demotown",
"customer_id": "727",
"property_id": "02010",
"services": [
{
"description": "Service1",
"shortname": "S1",
"orderdates": [
"2020-11-30",
"2020-12-14",
"2020-12-28"
]
},
{
"description": "Service2",
"shortname": "S2",
"orderdates": [
"2020-11-19",
"2020-12-17"
]
}
]
}
]
挑战在于需要生成 1 到 10 个服务之间的所有内容。为了创建上面的“静态”版本,我做了这个;
public class Anlobject
{
public string alias { get; set; }
public string address { get; set; }
public string city { get; set; }
public string customer_id { get; set; }
public string property_id { get; set; }
public Services services { get; set; }
public Services2 services2 { get; set; }
}
public class Services
{
public string description { get; set; }
public string shortname { get; set; }
public string[] dates { get; set; }
}
public class Services2
{
public string description { get; set; }
public string shortname { get; set; }
public string[] dates { get; set; }
}
private static Anlobject CreateAnlobject()
{
var obj = new Anlobject()
{
alias = "H02010",
address = "Demoroad 9",
city = "Demotown",
customer_id = "727",
property_id = "02010",
services = new Services()
{
description = "Service1",
shortname = "S1",
orderdates = new string[] { "2020-01-01","2020-02-01"},
},
services2 = new Services2()
{
description = "Service2",
shortname = "S2",
orderdates = new string[] { "2020-01-01", "2020-02-01" },
},
};
return obj;
}
private void bTest_Click(object sender, EventArgs e)
{
var obj = CreateAnlobject();
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
File.WriteAllText("c:\\temp\\jSonTestTK.json", json.ToString());
}
有没有办法只拥有一个 Services() 但多次调用它,还是我完全走错了路?
在此先感谢您提供查找或搜索的任何提示。
解决方案
你不需要(或想要)一个Services2
类或services2
属性。该services
属性是对象的集合Services
。(虽然我会推荐Service
该类的名称。)
该属性将是这样的:
public IEnumerable<Services> services { get; set; }
并像这样初始化它:
services = new List<Services>
{
new Services()
{
description = "Service1",
shortname = "S1",
orderdates = new string[] { "2020-01-01","2020-02-01"},
},
new Services()
{
description = "Service2",
shortname = "S2",
orderdates = new string[] { "2020-01-01", "2020-02-01" },
}
}
推荐阅读
- arrays - Scala 数组的大小(按字节)
- java - 如何使用 Map 方法向 HIbernate 5 提供实体包?
- javascript - 这个方法在 React.js 中执行什么?
- angular - 如何共享所有应用程序共有的 Angular 6 中的所有核心文件和文件夹?
- c# - 执行顺序/逻辑是什么:Task.Run(async() => await someAsyncMethod();)
- angular - Angular 6 X-editable with ngx-datatable
- javascript - 欧芹验证器中带有输入键的下一步按钮
- python - Python,使用字典的高效并行操作
- asp.net-core - 如何按实现类型解析服务?
- java - 池中没有可用的连接,netstat 在 Recv-Q 中显示非零值