Search code examples
c#jsonasp.net-mvcsystem.text.json

Error when run json code will not convert


For some reason the api data is not converting to a C# object. My IDE isn't throwing a fit. It only throws an error when I run it.

using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using pdrake.Models;

namespace pdrake.Controllers
{
    public class MovieController : Controller
    {
        private string baseUrl = "https://api.themoviedb.org/3/discover/movie?api_key=my_key&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1";
        public List<MovieResults> MovieList = new List<MovieResults>();
        public async Task<IActionResult> GetMovies()
        {
            using (HttpClient httpClient = new HttpClient())
            {
                var apiResponse = await httpClient.GetAsync(baseUrl);
                string apiData = await apiResponse.Content.ReadAsStringAsync();
                MovieList = JsonSerializer.Deserialize<List<MovieResults>>(apiData);
                ViewBag.Movie = MovieList;
                return View();
            }
        }
    }
}

Solution

  • Change your return statement to

    return Ok(MovieList):
    

    You should read up on MS Documentation on IActionResult

    UPDATE

    The problem you have is the data you are deserializing. You need to do the following to make it work.. and this is why

    the response you get is the following json:

    {
      "page": 1,
      "results": [ 
        {
          "adult": false,
          "backdrop_path": "/tYkMtYPNpUdLdzGDUTC5atyMh9X.jpg",
          "genre_ids": [
            28,
            53,
            80,
            18
          ],
          "id": 553604,
          "original_language": "en",
          "original_title": "Honest Thief",
          "overview": "A bank robber tries to turn himself in because he's falling in love and wants to live an honest life...but when he realizes the Feds are more corrupt than him, he must fight back to clear his name.",
          "popularity": 2431.379,
          "poster_path": "/zeD4PabP6099gpE0STWJrJrCBCs.jpg",
          "release_date": "2020-09-03",
          "title": "Honest Thief",
          "video": false,
          "vote_average": 7,
          "vote_count": 244
        }, {} ... ],
      "total_Pages": 500,
      "total_results": 10000
    }
    

    The response you are deserializing is an object that contains a list of movies in the "results" property. Use the following as your classes to get it working right.

    public class RootObject 
    {
      [JsonProperty("page")]
      public int Page {get;set;}
    
      [JsonProperty("results")]
      public List<MovieTitle> Results {get;set;}
    
      [JsonProperty("total_pages")]
      public int TotalPages {get;set;}
     
      [JsonProperty("total_results")]
      public int TotalResults {get;set;}  
    }
    
    public class MovieTitle 
    {
      [JsonProperty("adult")]
      public bool IsAdult {get;set;}
      
      [JsonProperty("original_title")]
      public string OriginalTitle {get;set;}
    
      ... // you can fill in the rest here
    }
    

    and the deserialization will happen at the rootObject level.

    var rootObject = JsonSerializer.Deserialize<RootObject>(apiData);
    var movieList = rootObject.Results;
    return Ok(movieList);