我想解析json而不输入它的路径:
我有https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=tf2%20Hats%20Summer%20Shades%20site:wiki.teamfortress.com/wiki/,如何从unescapedUrl获取字符串?
如何在没有路径的情况下制作它,所以我有[和{,我怎么能用它。
我的代码是
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"];
但后来我收到了错误......
感谢您的帮助,
-Krypton
答案 0 :(得分:0)
您可以使用DescendantsAndSelf()
查找具有"unescapedUrl"
名称的所有后代属性。但由于DescendantsAndSelf()
仅定义为JContainer
,因此我认为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"
您会看到结果数组中实际上有四个responseData.results[0].unescapedUrl
responseData.results[1].unescapedUrl
responseData.results[2].unescapedUrl
responseData.results[3].unescapedUrl
属性:
i
访问数组元素root["responseData"]["results"][i]["unescapedUrl"]
的语法是:
var firstUrl = (string)query.FirstOrDefault();
但是用Linq访问它们可能会更好:
{{1}}