我尝试通过使用HttpClient
请求的API访问基于另一个键的Json键的值。
我的代码正在从API中获取JSON,但我没有成功地定位特定的键并获取该数据。
有一个名为iso_1366_1
的密钥,它列出了一个国家代码(US,Au,GB等),其中包括一个名为certification
的密钥。我试图只返回证书密钥的值,如果iso_1366_1 == "US"
的值。当我执行代码时,Rating
的值是null
。
public static async Task getHttpApi()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.themoviedb.org/3/movie/54597/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("release_dates?api_key=key");
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
var dynamicObject = JsonConvert.DeserializeObject<dynamic>(result)!;
var Rating = dynamicObject.certification;
if (dynamicObject.iso_3166_1 == "US")
{
Console.WriteLine(Rating);
}
}
}
else
{
Console.WriteLine("Error");
}
}
}
catch (Exception err)
{
throw err;
}
//return "";
}
下面是作为响应对象返回的Json:
{"id":54597,"results":[{"iso_3166_1":"FR","release_dates":[{"certification":"","descriptors":[],"iso_639_1":"","note":"","release_date":"2011-09-19T00:00:00.000Z","type":3}]},{"iso_3166_1":"NL","release_dates":[{"certification":"16","descriptors":[],"iso_639_1":"","note":"","release_date":"2011-07-21T00:00:00.000Z","type":3}]},{"iso_3166_1":"US","release_dates":[{"certification":"R","descriptors":[],"iso_639_1":"","note":"","release_date":"2011-04-26T00:00:00.000Z","type":3}]},{"iso_3166_1":"AU","release_dates":[{"certification":"R18+","descriptors":[],"iso_639_1":"","note":"","release_date":"2011-04-25T00:00:00.000Z","type":3}]},{"iso_3166_1":"GB","release_dates":[{"certification":"18","descriptors":[],"iso_639_1":"","note":"","release_date":"2011-09-26T00:00:00.000Z","type":3}]},{"iso_3166_1":"DE","release_dates":[{"certification":"18","descriptors":[],"iso_639_1":"de","note":"","release_date":"2011-09-19T00:00:00.000Z","type":3}]}]}
我没有清理json的内容,因为我想让你看看我在结果中看到了什么。我做错了什么?
谢谢!
2条答案
按热度按时间rryofs0p1#
你的JSON响应不是你的代码试图访问的:
我不知道JSON.NET是如何解析dynamic的,但你需要在访问属性之前访问数组元素。它应该是这样的:
下次你应该将你的JSON粘贴到一个JSON编辑器(甚至像你的浏览器Javascript控制台一样简单),并确保你的JSON是正确的。
flvtvl502#
在你知道你需要它做什么之前不要使用dynamic。Dynamic只是字典的另一种语法,它的工作速度更慢,因为它有一个额外的层。在这种情况下,你可以尝试LINQ到JSON
或更长的路