我正在尝试从 JSON 填充模型。我正在使用 Newtonsoft.Json.JsonConvert。
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(urlhere);
httpWebRequest.Credentials = new NetworkCredential("un", "pw");
httpWebRequest.Method = "Get";
httpWebRequest.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
string incomingItemAsJson = streamReader.ReadToEnd(); // should be the json response as a string
MyObject myObject= JsonConvert.DeserializeObject<MyObject>(incomingItemAsJson);
我正在努力访问(并遍历)Json 中的子元素。
{
"field1": "blah blah",
"field2": "blah blah",
"field3": [(2)
{
"field3Item1Id": "xxx",
"field3Item1Value": "Goo"
},-
{
"field3Item2Id": "xxx",
"field3Item2Value": "Foo"
}-
],-
"field4": {
"field4Id": xxx,
"field4Value": "Moo"
}-
}
我想将此信息映射到模型,如下所示:
public class MyObject
{
public string field1 {get;set;} //blah blah
public string field2 {get;set;} //blah blah
public string field3 {get;set;} //Goo, Foo
public string field4 {get;set;} //Moo
}
Field1 和 field2 被分配给 MyObject 中的字符串属性 - 没有问题。
我的问题:
字段3
如何将每个项目的值部分连接成一个字符串,例如:“Goo, Foo”?
字段4
field4 中只会有一个子元素。
有没有一种简单的方法来仅提取 Value 部分并将其映射到 MyObject 中的字符串属性?