如何在 C# 列表中添加对象数组<T>
How to add an Array of Object in a C# List<T>
我必须创建如下所示的内容,一个 JSON 字符串:
{
"sync": {
"email": "dummy@dummy.com",
"first": "James",
"last": "Dawson",
"cell": "2120980989",
"valueOfField": [
{
"number": "1",
"content": "second"
},
{
"number": "10",
"content": "Y"
}
/* more as needed */
]
}
}
valueOfField
之前我什么都能做。
这是我的代码:
sync cu = new sync();
cu.first = "James";
cu.last = "Doe";
cu.email = "jdoe@goesnowhere.com";
cu.cell = "999-999-9999";
/*for (int i = 0; i < 2; i++)
{
cu.valueOfField.Add("1", "106-93-0909");
cu.valueOfField.Add("5", "12/3/1995");
}*/
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new { sync = cu });
...
public class sync
{
public string first;
public string last;
public string email;
public string cell;
/*public IDictionary<string, string> valueOfField;*/
}
我尝试添加 IDictionary
,但没有成功。
我可以在创建 valueOfField
时得到一些帮助吗?
您需要另一个 class 作为 valueOfs
public class ValueOf{
public string number {get;set;}
public string content {get;set;}
}
然后
public class sync
{
public string first;
public string last;
public string email;
public string cell;
public List<ValueOf> valueOfField = new List<ValueOf>();
}
现在
cu.valueOfField.Add(new ValueOf{
Number="1", Content = "106-93-0909"
});
cu.valueOfField.Add(new ValueOf{
Number = "5", Content = "12/3/1995");
});
我必须创建如下所示的内容,一个 JSON 字符串:
{
"sync": {
"email": "dummy@dummy.com",
"first": "James",
"last": "Dawson",
"cell": "2120980989",
"valueOfField": [
{
"number": "1",
"content": "second"
},
{
"number": "10",
"content": "Y"
}
/* more as needed */
]
}
}
valueOfField
之前我什么都能做。
这是我的代码:
sync cu = new sync();
cu.first = "James";
cu.last = "Doe";
cu.email = "jdoe@goesnowhere.com";
cu.cell = "999-999-9999";
/*for (int i = 0; i < 2; i++)
{
cu.valueOfField.Add("1", "106-93-0909");
cu.valueOfField.Add("5", "12/3/1995");
}*/
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new { sync = cu });
...
public class sync
{
public string first;
public string last;
public string email;
public string cell;
/*public IDictionary<string, string> valueOfField;*/
}
我尝试添加 IDictionary
,但没有成功。
我可以在创建 valueOfField
时得到一些帮助吗?
您需要另一个 class 作为 valueOfs
public class ValueOf{
public string number {get;set;}
public string content {get;set;}
}
然后
public class sync
{
public string first;
public string last;
public string email;
public string cell;
public List<ValueOf> valueOfField = new List<ValueOf>();
}
现在
cu.valueOfField.Add(new ValueOf{
Number="1", Content = "106-93-0909"
});
cu.valueOfField.Add(new ValueOf{
Number = "5", Content = "12/3/1995");
});