skip to Main Content

I’m trying to access the value of a Json key based on the value of another key via an API using HttpClient request.

My code is getting back the Json from the API but I’m not successful with targeting the specific key and getting back that data.

There is a key called iso_1366_1 that lists a country code (US, AU, GB, etc) that includes a key called certification. I’m trying to return only the value of the certification key if the value of iso_1366_1 == "US". When I execute the code, the value for Rating is 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 "";
    }

Here is the Json that is returned as the response object:

{"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}]}]}

I didn’t clean up the json content since I wanted you to see what I’m seeing in my results.
What am I doing wrong?

Thanks!

2

Answers


  1. Your JSON response is not what your code is trying to access:

    enter image description here

    I don’t know how JSON.NET parses dynamic but you need to access the array element before accessing the property. It should be something like:

    dynamicObject.results[0].iso_3166_1
    

    Next time you should paste your JSON into a JSON editor (even as simple as your browser Javascript console) and make sure your JSON is correct.

    Login or Signup to reply.
  2. Never use dynamic untill you know what do you need it for. Dynamic just another syntax for a dictionary, and it works even slower since it has an extra layer. In this case you can try LINQ to 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"
    

    or longer way

        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");
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search