运行 json 代码无法转换时出错

Error when run json code will not convert

出于某种原因,api 数据未转换为 C# 对象。我的 IDE 没有大发脾气。它只会在我 运行 时抛出错误。

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();
            }
        }
    }
}

将您的 return 语句更改为

return Ok(MovieList):

您应该阅读 MS Documentation 上的 IActionResult

更新

您遇到的问题是您正在反序列化的数据。您需要执行以下操作才能使其正常工作……这就是为什么

您得到的响应如下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
}

您要反序列化的响应是一个对象,其中包含“结果”属性 中的电影列表。使用以下内容作为您的 类 使其正常工作。

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
}

并且反序列化将发生在 rootObject 级别。

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