Search code examples
c#jsonasp.net-mvc-5themoviedb-api

ASP.NET MVC 5 getting a JSON result from TMDB API


How is it possible to let users search for a movie using TMDB API (The Movie Db) in an ASP.NET MVC 5 application and return a JSON result.

Working example outside VB using my personel api key and returning a json result with all the movies containing the string "mission":

http://api.themoviedb.org/3/search/movie?api_key=841c..&query=mission

The documentation (http://docs.themoviedb.apiary.io/#reference/search/searchmovie) suggest to use the following code for C#:

var baseAddress = new Uri("http://api.themoviedb.org/3/");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");

    using(var response = await httpClient.GetAsync("search/movie"))
    {
        string responseData = await response.Content.ReadAsStringAsync();
    }
}

I paste the code into an async action MovieSearch() but clueless what to do now.


Solution

  • You have to Deserialize the JSON string they return you as responseData into c# type like Movie. For the Deserialization you can use library like JSON.NET then write your like this:

    class Movie
    {
       public string Name{ get; set;}
       public decimal Rating{ get; set;}
    }
    
     string output = "{ "Name": "The Matrix", "Rating": "4.0"}"
    
    Movie deserializedMovie = JsonConvert.DeserializeObject<Movie>(responseData);
    

    Check what actually they return cause the response can contain not a single Movie object but is can contain a List then you have to write your code like this:

    List<Movie> movies= JsonConvert.DeserializeObject<List<Movie>>(responseData);
    

    Hope this helps :)