没有完整路径解析json [英] Parse json without full path

查看:86
本文介绍了没有完整路径解析json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析json而不输入路径:

I want to parse json without entering the path to it:

我有

I have https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=tf2%20Hats%20Summer%20Shades%20site:wiki.teamfortress.com/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("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=tf2%20Hats" + itemname + "%20site:wiki.teamfortress.com/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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆