我想解析json而不输入路径:
I want to parse json without entering the path to it:
我有 ajax.googleapis/ajax/services/search/images?v=1.0&q=tf2%20Hats%20Summer%20Shades%20site:wiki.teamfortress /wiki/,如何从unescapedUrl获取字符串?
I have ajax.googleapis/ajax/services/search/images?v=1.0&q=tf2%20Hats%20Summer%20Shades%20site:wiki.teamfortress/wiki/ , How can i get the string from unescapedUrl?
我如何在没有路径的情况下制作它,所以我有那些[和{,我该如何使用它.
How can i make it without the path, so i have those [ and {, How can i use it.
我的代码是
string itemname = "Hat with no name"; var webClient = new System.Net.WebClient(); var json = webClient.DownloadString("ajax.googleapis/ajax/services/search/images?v=1.0&q=tf2%20Hats" + itemname + "%20site:wiki.teamfortress/wiki/"); Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(json); string HatURL = (string)o["responseData"]["results"]["unescapedUrl"];但是我得到一个错误...
But then i get an error...
感谢您的帮助,
-rypto
推荐答案您可以使用 DescendantsAndSelf() 查找具有"unescapedUrl"名称的所有后代属性.但是,由于仅为JContainer定义了DescendantsAndSelf(),因此我发现 extend 到JToken:
You can use DescendantsAndSelf() to find all descendant properties with the "unescapedUrl" name. But since DescendantsAndSelf() is only defined for JContainer I find it helpful to extend it to JToken:
public static IEnumerable<JToken> DescendantsAndSelf(this JToken node) { if (node == null) return Enumerable.Empty<JToken>(); var container = node as JContainer; if (container != null) return container.DescendantsAndSelf(); else return new [] { node }; }然后像这样使用它:
var root = JToken.Parse(json); var query = root.DescendantsAndSelf().OfType<JProperty>().Where(p => p.Name == "unescapedUrl"); foreach (var property in query) { Debug.WriteLine(property.Path); var url = (string)property; // process the unescapedUrl somehow. }您将看到结果数组中实际上有四个"unescapedUrl"属性:
You will see that there are actually four "unescapedUrl" properties in an array of results:
responseData.results[0].unescapedUrl responseData.results[1].unescapedUrl responseData.results[2].unescapedUrl responseData.results[3].unescapedUrl访问数组元素i的语法为:
The syntax to access element i of the array would be:
root["responseData"]["results"][i]["unescapedUrl"]但是最好使用Linq访问它们:
But it would probably be better to access them with Linq:
var firstUrl = (string)query.FirstOrDefault();更多推荐
没有完整路径解析json
发布评论