我正在尝试从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中的字符串属性 - 没问题。
我的问题:
Field3
如何将每个项目的Value部分连接成一个字符串,如下所示:“Goo,Foo”?
Field4
field4中只有一个子元素。
是否有一种简单的方法可以仅提取Value部分并将其映射到MyObject中的字符串属性?
答案 0 :(得分:0)
Newton的JSON只是简单地创建了映射,如果在这种情况下没有类似的结构化对象,可能无法更改JSON的结构,因为它可能来自其他源,因此您可以更改Model类像..
public class MyObject
{
public string field1 {get;set;}
public string field2 {get;set;}
public Dictionary<string, string> field3 {get;set;}
public Dictionary<string, string> field4 {get;set;}
}
应该这样做......