【发布时间】:2011-11-02 15:43:13
【问题描述】:
我已经使用 silverlight 的 System.JSON 找到了答案,但规格发生了变化,现在我需要在 .NET 3.5 中完成
这是我得到的 JSON
{"SearchResults":[{"PageCount":"1"},
{"SEARCHVAL":"Result","CATEGORY":"Category1","X":"1","Y":"2"},
{"SEARCHVAL":"AnotherResult","CATEGORY":"Category1","X":"2","Y":"2"}]}
使用 System.JSON 程序集的解决方案是
var resultList = ((JsonArray)searchResults["SearchResults"])
.OfType<JsonObject>()
.Where(o => o.ContainsKey("SEARCHVAL"))
.Select(o => new SearchResult() {
SearchValue = o["SEARCHVALUE"],
Category = o["CATEGORY"].
X = o["X"],
Y = o["Y"]
}).ToList();
我认为大部分代码都相似/完全相同,但我不确定 ContainsKey 在 JSON.net 中的对应部分。我认为它是 Contains() 方法,但我不确定如何使用它以便获得 SEARCHVAL 的 X 和 Y。
更新:
这是我获取 JSON 流和解析的代码:
...
Uri uri = new Uri(url);
WebClient client = new WebClient();
ParseJSON(client.OpenRead(uri));
}
private void ParseJSON(Stream stream)
{
if (stream == null)
return;
StreamReader reader = new StreamReader(stream);
JObject searchResult = JObject.Parse(reader.ReadLine());
string x= searchResult["SearchResults"][0]["SEARCHVAL"]["X"].ToString();
string y= searchResult["SearchResults"][0]["SEARCHVAL"]["Y"].ToString();
// use data
...
我在string lat = searchresult... 上得到一个空异常。任何线索我在使用 JSON.NET 时哪里出错了?
【问题讨论】:
标签: .net linq json .net-3.5 json.net