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

时间:2019-07-09 20:57:03

标签: c# omdbapi

我启动了一个新应用程序,该应用程序使用Omdb API检索电影信息。该应用程序的目标是使用搜索关键字来检索电影标题。例如:“ shawshank”应返回:

{"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中提取电影标题。使用的Nuget是: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.


1 个答案:

答案 0 :(得分:0)

实际上您在尝试将响应直接转换为MovieModel,而实际上根对象具有Search这样的数组字段。

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

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

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