C# HttpClient反序列化JSON响应内容-如何选择键值

y1aodyip  于 2023-04-22  发布在  C#
关注(0)|答案(2)|浏览(146)

我尝试通过使用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的内容,因为我想让你看看我在结果中看到了什么。我做错了什么?
谢谢!

rryofs0p

rryofs0p1#

你的JSON响应不是你的代码试图访问的:

我不知道JSON.NET是如何解析dynamic的,但你需要在访问属性之前访问数组元素。它应该是这样的:

dynamicObject.results[0].iso_3166_1

下次你应该将你的JSON粘贴到一个JSON编辑器(甚至像你的浏览器Javascript控制台一样简单),并确保你的JSON是正确的。

flvtvl50

flvtvl502#

在你知道你需要它做什么之前不要使用dynamic。Dynamic只是字典的另一种语法,它的工作速度更慢,因为它有一个额外的层。在这种情况下,你可以尝试LINQ到JSON

string json = await content.ReadAsStringAsync();

    JArray results = (JArray)JObject.Parse(json)["results"];

     var Rating = (string)results
                        .Where(x => (string)x["iso_3166_1"] == "US")
                        .SelectMany(x => x["release_dates"]
                        .Select(y => y["certification"]))
                        .FirstOrDefault(); // "R"

或更长的路

var usCertification = results.Where(x => (string)x["iso_3166_1"] == "US")
                        .SelectMany(x => x["release_dates"])
                        .FirstOrDefault();

    if (usCertification != null)
    {
        string Rating = (string)usCertification["certification"]; // "R"

        Console.WriteLine(Rating);
    }
    else
    {
        Console.WriteLine("Error");
    }

相关问题