C#对象的外观如何,在序列化json后看起来像这样吗? 已经花了几个小时,无法弄清楚如何将电子邮件作为变量?只有一个“前景”和多个孩子。
{
"prospects": {
"1234": {
"first_name": "New first name",
"last_name": "New last name"
},
"some@email.com": {
"first_name": "New first name",
"last_name": "New last name"
},
"some.other@email.com": {
"first_name": "New first name",
"last_name": "New last name"
}
}
}
最终结果应该是
答案 0 :(得分:2)
您的问题是您的“键”是动态的。这意味着您不能硬编码。试试这个:
public class RootObject
{
[JsonProperty("prospects")]
public Dictionary<string, NameModel> Prospects { get; set; }
}
public class NameModel
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
}
从那里您可以像这样构建对象:
var model = new RootObject()
{
Prospects = new Dictionary<string, NameModel>()
{
{ "1234", new NameModel() { FirstName = "Sam", LastName = "Test" }},
{ "some@email.com", new NameModel() { FirstName = "Sue", LastName = "Test" }},
{ "some.other@email.com", new NameModel() { FirstName = "Frank", LastName = "Test" }},
}
};
导致此Json发生的原因:
{
"prospects": {
"1234": {
"firstName": "Sam",
"lastName": "Test"
},
"some@email.com": {
"firstName": "Sue",
"lastName": "Test"
},
"some.other@email.com": {
"firstName": "Frank",
"lastName": "Test"
}
}
}
提琴here