[英]JSON.NET Deserialize Nested data from URL
我正在嘗試通過本地主機將JSON數據輸入命令行。 當我通過Web瀏覽器瀏覽頁面時,以下JSON被重新調整:(我使用的是VS 2008)
(http://LocalHost/example/00012/json.sp)
{"errors":[],
"valid":true,
"results":[{"address1":"2000 MAX1MAX2 ROAD","city":"Sunny City ","state":"FL","zip":"00012"}]}
我希望能夠在利用嵌套對象(列表)的同時調用數據,以便能夠從該對象調用參數。 這是我到目前為止所擁有的。 對於公共類,我的代碼中包含以下內容:
public class Result
{
public string address1 { get; set; }
public string city { get; set; }
public sting state { get; set; }
public sting zip { get; set; }
}
public class RObject
{
public List<object> errors { get; set; }
public bool valid { get; set; }
public List<Result> results { get; set; }
}
這是我用來獲取數據的代碼:
var request = WebRequest.Create("http://local4510/example/00012/json.sp ");
WebResponse response = request.GetResponse();
string json;
using (var sr = new StreamReader(response.GetResponseStream()))
{
json = sr.ReadToEnd();
}
JObject jResult = JObject.Parse(json); // Parses the data
Result me = new Result()
{
Me.address1 = (string)jResult["results"][" address1 "]
Me city = (string)jResult["results"][" city "]
Me state = (string)jResult["results"][" state "]
Me zip = (string)jResult["results"]["zip"]
};
//Console.Write(jResult); working
Console.Write(me.address1+ ”--” + me.city+”--” + me.state+”--”+ me.zip)
Console.Read();
除了一些語法錯誤外,您的主要問題是您沒有將“結果”作為結果數組對待。代碼看起來應該更像這樣……
Result me = new Result()
{
address1 = (string)jResult["results"][0]["address1"],
city = (string)jResult["results"][0]["city"] ,
state = (string)jResult["results"][0]["state"] ,
zip = (string)jResult["results"][0]["zip"]
};
...注意,硬編碼的[0]偏移量用於訪問結果數組中的第一個結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.