无法从 Omdb API 检索 json 并将其合并到我的电影类中,显示对象内所有参数的"null"



我启动了一个利用 Omdb API 检索电影信息的新应用程序。 应用程序的目标是使用搜索关键字检索电影标题。 例如:"肖申克"应返回:

{"Search":[{"Title":"The Shawshank Redemption","Year":"1994","imdbID":"tt0111161","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMDFkYTc0MGEtZmNhMC00ZDIzLWFmNTEtODM1ZmRlYWMwMWFmXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg"},{"Title":"Shawshank: The Redeeming Feature","Year":"2001","imdbID":"tt0293927","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BYjgwMjNjOGUtNzU3MC00MGM5LTk4NTctNGI5N2I2NGI0YjBhXkEyXkFqcGdeQXVyMjIzMTk0MzM@._V1_SX300.jpg"},{"Title":"Hope Springs Eternal: A Look Back at 'The Shawshank Redemption'","Year":"2004","imdbID":"tt0443041","Type":"movie","Poster":"N/A"},{"Title":"The Shawshank Redemption: Cast Interviews","Year":"2004","imdbID":"tt5443390","Type":"movie","Poster":"N/A"},{"Title":"The Shawshank Redemption (Scene)","Year":"2012","imdbID":"tt2477746","Type":"movie","Poster":"N/A"},{"Title":"The Shawshank Reflection","Year":"2015","imdbID":"tt3882670","Type":"movie","Poster":"N/A"},{"Title":"The Shawshank Redemption: Behind the Scenes","Year":"2004","imdbID":"tt5443386","Type":"movie","Poster":"N/A"}],"totalResults":"7","Response":"True"}

问题是一旦我运行我的表单应用程序,我就会尝试将 json 保存到一个对象中,假设如果我的对象参数相同(不区分大小写)名称,JSON 项将保存到对象内的相应变量中。由于对象参数保持为空,因此不会发生这种情况。

这段代码是通过关注一个关于制作一个使用 API 提取在线漫画的应用程序的 youtube 视频制作的。我想从 Omdb 中提取电影标题。使用的Nugets是:Microsoft.AspNet.WebApi.Client v5.2.7和Newtonsoft.Json v12.0.2。用于制作此内容的视频链接如下: https://www.youtube.com/watch?v=aWePkE2ReGw

我尝试在浏览器中测试我的网址,它成功生成了所需的 JSON。我还尝试单步执行代码并观察变量,我注意到没有数据成功从 url 中提取。我对建立HTTP连接以及使用API非常陌生,因此这可能是一个简单的解决方案。运行代码后,被监视变量的结果如下:

Name              Value               Type
Title           "MainWindow"          string
movie   {Movie_application.MovieModel}  Movie_application.MovieModel
Film.Title     null               string
url"http://www.omdbapi.com/?s=shawshank&apikey=568027e4" string
Tag            null               object
Title           "MainWindow"             string
Film    {Movie_application.MovieModel}  Movie_application.MovieModel
titlee             null                 string

mainwindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Movie_application
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//Start up the tcp/ip connection via HTTPclient 
APIhelper.InitializeClient();
}
private async Task LoadResponseText(string Tag)
{
//grab the movie and put it in a local variable
var Film = await MovieProcessor.LoadMovie(Tag);
//create the full url of the poster 
//var uriSource = new Uri(Film.Poster, UriKind.Absolute);
//create a bitmap image out of url and put it in the display of the WP window
//MoviePoster.Source = new BitmapImage(uriSource);
Result_Text.Text = Film.Title;
}
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
await LoadResponseText("shawshank");
}
private async void SearchBtn_Click(object sender, RoutedEventArgs e)
{
await LoadResponseText(SearchBox.Text);
}
}
}

```APIhelper```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Movie_application
{
public class  APIhelper
{
public static HttpClient ApiClient { get; set; }
public static void InitializeClient()
{
//Create a new HttpClient object
ApiClient = new HttpClient();
//Clear headers out of HttpClient
ApiClient.DefaultRequestHeaders.Accept.Clear();
//Adds a header which requests a JSON data rather than web page tags etc.
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
}
```MovieProcessor```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Movie_application
{
public class MovieProcessor
{

public static async Task<MovieModel> LoadMovie(string search)
{
string url = "http://www.omdbapi.com/?s=" + search + "&apikey=568027e4";
//call HTTPclient to open connection and await a response from destination
using (HttpResponseMessage response = await APIhelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
//read in the response data in an asynch fashion 
MovieModel movie = await response.Content.ReadAsAsync<MovieModel>();
string titlee = movie.Title;
return movie;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}
```MovieModel```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Movie_application
{
public class MovieModel
{
public string Title  { get; set; }
public string Poster { get; set; }
}
}

I expect the code to be able to write "The Shawshank Redemption" onto the form text box. The text box remains empty at the end of the run. Thanks in advance.

看起来您正在尝试将响应直接投射到 MovieModel,而实际上根对象具有类似数组Search字段。

{"Search":[...], "totalResults":"7", "Response":"True"}

因此,要解决此问题,您必须创建一个表示此根对象的模型,并具有一个名为Search的字段,该字段是MovieModel数组。

然后更改MovieModel movie = await response.Content.ReadAsAsync<MovieModel>();以返回您创建的任何新模型

最新更新