0

I started a new application which utilizes the Omdb API to retrieve movie information. the goal of the application is to retrieve a movie title using a search keyword. ex: "shawshank" should return :

{"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"}

The problem is once I run my form application, I attempt to save the json into an object assuming that if my object parameters are the same (case insensitive) name the JSON items will be saved into the corresponding variables inside the object. This does not happen as the object parameters remain null.

This code was made by following a youtube video about making an app which pulls an online comic using an API. I wanted to instead pull movie titles from the Omdb. Nugets which were used are: Microsoft.AspNet.WebApi.Client v5.2.7 and Newtonsoft.Json v12.0.2. The link of the video which was used to make this is as follows: https://www.youtube.com/watch?v=aWePkE2ReGw

I have tried testing my url in browser and it successfully generates the desired JSON. I have also tried stepping through the code and watching variables I noticed that no data is successfully being pulled from the url. I am very new to making HTTP connections as well as using API's so it might be an easy fix. After running the code the results of the variables being watched are as follows:

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.


Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108

1 Answers1

0

It looks like you're trying to cast the response directly to a MovieModel when in fact the root object has fields like Search which is an array.

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

So to fix this you'd have to create a model which represents this root object and has a field called Search which is an array of MovieModel.

Then change MovieModel movie = await response.Content.ReadAsAsync<MovieModel>(); to return whatever new model you create

David Liaw
  • 3,193
  • 2
  • 18
  • 28