Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am trying to fetch Data from API with Key.

I am trying to fetch in Windows Forms application.

I am able to fetch the data but when I try to display that data in datagridview, it shows an error message like:

Cannot deserialize the current JSON object (e.g., <code>{\"name\":\"value\"}</code>) into type because the type requires a JSON array (e.g. <code>[1,2,3]</code>) to deserialize correctly.


When I check value of the body variable, I get data like this:

"{\"movie_results\":[{\"title\":\"Hum Tum and Them\",\"year\":2019,\"imdb_id\":\"tt10045256\"},
{\"title\":\"Hum Tum Aur Ghost\",\"year\":2010,\"imdb_id\":\"tt1465493\"},
{\"title\":\"Hum Tum Aur Woh\",\"year\":1971,\"imdb_id\":\"tt0378073\"},
{\"title\":\"Hum Tum Dushman Dushman\",\"year\":2015,\"imdb_id\":\"tt6002986\"},
{\"title\":\"Hum Tum Pe Marte Hain\",\"year\":1999,\"imdb_id\":\"tt0226786\"},
{\"title\":\"Hum Tum Shabana\",\"year\":2011,\"imdb_id\":\"tt2034011\"},
{\"title\":\"Hum Tum\",\"year\":2004,\"imdb_id\":\"tt0378072\"},
{\"title\":\"Hum Tum\",\"year\":2014,\"imdb_id\":\"tt10039022\"},
{\"title\":\"Hum Tumhare Hain Sanam\",\"year\":2002,\"imdb_id\":\"tt0222024\"}],
\"search_results\":9,\"status\":\"OK\",\"status_message\":\"Query was successful\"}"

So now, I want to display this data in datagrid view.
I have also tried this:
JavaScript
var result2 = JsonConvert.DeserializeObject<List<MovieNew>>(body);

but get Cannot deserialize error.

What I have tried:

C#
public class MovieNew
{
	public string title { get; set; }
	public int year { get; set; }
    public string imdb_id { get; set; }
}

public async void Test_Api_With_Autentication()
{
String s = "https://movies-tv-shows-database.p.rapidapi.com/?title";
   
string movieName = System.Web.HttpUtility.UrlPathEncode(txtMovieName.Text);
s = s + "=" + movieName;

string finalMovieName = s;

var client = new HttpClient();

var request = new HttpRequestMessage
{
	Method = HttpMethod.Get,
    RequestUri = new Uri(finalMovieName),
    Headers =
    {
			{ "Type", "get-movies-by-title" },
			{ "X-RapidAPI-Key", "My API KEY" },
			{ "X-RapidAPI-Host", "movies-tv-shows-database.p.rapidapi.com" },
	},
};

using (var response = await client.SendAsync(request))
{
    var body = await response.Content.ReadAsStringAsync();
}
}
Posted
Updated 2-Oct-23 3:40am
v2

Your MovieNew class does not match the JSON.
If I convert the "display" string to a genuine JSON string:
JSON
{"movie_results":[{"title":"Hum Tum and Them","year":2019,"imdb_id":"tt10045256"},
{"title":"Hum Tum Aur Ghost","year":2010,"imdb_id":"tt1465493"},
{"title":"Hum Tum Aur Woh","year":1971,"imdb_id":"tt0378073"},
{"title":"Hum Tum Dushman Dushman","year":2015,"imdb_id":"tt6002986"},
{"title":"Hum Tum Pe Marte Hain","year":1999,"imdb_id":"tt0226786"},
{"title":"Hum Tum Shabana","year":2011,"imdb_id":"tt2034011"},
{"title":"Hum Tum","year":2004,"imdb_id":"tt0378072"},
{"title":"Hum Tum","year":2014,"imdb_id":"tt10039022"},
{"title":"Hum Tumhare Hain Sanam","year":2002,"imdb_id":"tt0222024"}],
"search_results":9,"status":"OK","status_message":"Query was successful"}
And run it through a Json to C# converter[^] I get these classes:
C#
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
    public class MovieResult
    {
        public string title { get; set; }
        public int year { get; set; }
        public string imdb_id { get; set; }
    }

    public class Root
    {
        public List<MovieResult> movie_results { get; set; }
        public int search_results { get; set; }
        public string status { get; set; }
        public string status_message { get; set; }
    }
Which is nothing like your single class:
C#
public class MovieNew
{
	public string title { get; set; }
	public int year { get; set; }
     public string imdb_id { get; set; }
}
...
var result2 = JsonConvert.DeserializeObject<List<MovieNew>>(body);
If the Json doesn't match the classes, you will rightly get an error...
 
Share this answer
 

You need to have suitable classes to deserialize the Json into. Something along these lines.


C#
public class Movie
 {
     public string? Title { get; set; }
     public int Year  { get; set; }
     public string? Imdb_Id { get; set; }

 }
 public class MoviesSummary
 {
     public Movie[]?Movie_Results { get; set; }
     public int Search_Results { get; set; }
     public string? Status { get; set; }

     public string? Status_Message { get; set; }
 }

Then you should be good to go like this


C#
    class Program
    {
        static void Main(string[] args)
        {
            string jsonString = $$"""
{"movie_results":[{"title":"Hum Tum and Them","year":2019,"imdb_id":"tt10045256"},
{ "title":"Hum Tum Aur Ghost","year":2010,"imdb_id":"tt1465493"},
{ "title":"Hum Tum Aur Woh","year":1971,"imdb_id":"tt0378073"},
{ "title":"Hum Tum Dushman Dushman","year":2015,"imdb_id":"tt6002986"},
{ "title":"Hum Tum Pe Marte Hain","year":1999,"imdb_id":"tt0226786"},
{ "title":"Hum Tum Shabana","year":2011,"imdb_id":"tt2034011"},
{ "title":"Hum Tum","year":2004,"imdb_id":"tt0378072"},
{ "title":"Hum Tum","year":2014,"imdb_id":"tt10039022"},
{ "title":"Hum Tumhare Hain Sanam","year":2002,"imdb_id":"tt0222024"}],
"search_results":9,"status":"OK","status_message":"Query was successful"
}
""";
          var moviesSummary = JsonSerializer.Deserialize<MoviesSummary>(jsonString,
                               new JsonSerializerOptions{PropertyNameCaseInsensitive=true});

            Console.ReadLine();
      }
   }
 
Share this answer
 
v2
To expand on what others have said, there are tools out there that can help you generate the classes from the JSON for you. My go to is: JSON Utils: Generate C#, VB.Net, SQL TAble and Java from JSON[^]

Here is a sample of classes generated:
C#
public class MovieResult
{

    [JsonProperty("title")]
    public string Title { getset; }

    [JsonProperty("year")]
    public int Year { getset; }

    [JsonProperty("imdb_id")]
    public string ImdbId { getset; }
}

public class Movies
{

    [JsonProperty("movie_results")]
    public IList<MovieResult> MovieResults { getset; }

    [JsonProperty("search_results")]
    public int SearchResults { getset; }

    [JsonProperty("status")]
    public string Status { getset; }

    [JsonProperty("status_message")]
    public string StatusMessage { getset; }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900