创建 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
public class Service //create class as singular
{
public string description { get; set; }
public string shortname { get; set; }
public string[] orderdates { get; set; }
}
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 List<Service> services { get; set; }
}
CreateAnlobject
功能
private static Anlobject CreateAnlobject()
{
var service1 = new Service()
{
description = "Service1",
shortname = "S1",
orderdates = new string[] { "2020-01-01", "2020-02-01" },
};
var service2 = new Service()
{
description = "Service2",
shortname = "S2",
orderdates = new string[] { "2020-01-01", "2020-02-01" },
};
var obj = new Anlobject()
{
alias = "H02010",
address = "Demoroad 9",
city = "Demotown",
customer_id = "727",
property_id = "02010",
services = new List<Service> { service1, service2}
};
return obj;
}
从 Main 方法调用该方法
var obj = CreateAnlobject();
var json = JsonConvert.SerializeObject(new List<Anlobject> { obj }); //you need list of Anlobject
File.WriteAllText("c:\\rnd\\jSonTestTK.json", json.ToString());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句