没有完整路径解析json

编程入门 行业动态 更新时间:2024-10-24 00:17:22
本文介绍了没有完整路径解析json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想解析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

本文发布于:2023-11-30 05:32:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648891.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   完整   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!