The Movie Database サポート

First off I'm new to JSON... I'm trying to incorporate this into a .NET 3.5 project and I really don't want to upgrade to a newer version of .NET so I don't upset any customers. I started off with LordMike's TMDbLib wrapper and started modifying it from the source code provided.

Here is the basic code I've got in C#:


public Movie GetMovie(string id, string language)
{

      Dictionary dict = new Dictionary();

            if (language != null)
                dict.Add("language", language);

            dict.Add("append_to_response", "alternative_titles,casts,images,releases,lists");

           String response = webGet("movie/" + id, dict);

      Movie resp = JsonConvert.DeserializeObject(response);

      return resp;
}



public String webGet(String methodName, Dictionary parameters) 
 { 

            String getUrl = (UseSsl ? "https://" : "http://") + BaseUrl + "/" + ApiVersion + "/" + methodName + "?api_key=" + ApiKey;

            int i = 0;
            if (parameters != null)
            {
                foreach (KeyValuePair param in parameters)
                {

                    getUrl += "&";


                    try
                    {
                        getUrl += param.Key + "=" + HttpUtility.UrlEncode(param.Value, System.Text.Encoding.UTF8);
                    }
                    catch (Exception e)
                    {
                        // ignore for now
                    }

                    i++;
                }
            }
            
            var json_data = string.Empty;

            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(getUrl);
                req.Method = WebRequestMethods.Http.Get;
                req.Accept = "application/json";
                req.ContentType = "applicaton/json;charset=utf-8";
                WebResponse resp = req.GetResponse();
                
                Stream stream = resp.GetResponseStream();
                StreamReader sr = new StreamReader(stream);

                json_data = sr.ReadToEnd();
            }
            catch { }

            return json_data;

          
 } 


In my Movie object only a few of the values are filling even though the apiary.io is showing me it is sending the info. For example, I'm getting a value for Title, but no image paths are filling, no production companies, and others. It is like some of the data isn't deserializing properly and I'm not sure why. LordMike's code works fine when I don't change it to use JSON.NET.

I see a couple of possible issues in the Response Header in apiary.io. It says content-type: application/json;charset=utf-8 (with ";charset=utf-8" crossed out) and the etag has a bunch of stuff crossed out with red boxes in several places.

Any ideas? Thanks!

I program on the side, so I'm not very good with the programming lingo or more advanced techniques. Thanks!

8 replies (on page 1 of 1)

Jump to last post

Can you post your Movie class and the JSON returned by the TMDb API?

Here is my Movie class:


public class Movie
    {
        public int Id { get; set; }
        public string ImdbId { get; set; }
        public string Title { get; set; }
        public string OriginalTitle { get; set; }
        public string Status { get; set; }
        public string Tagline { get; set; }
        public string Overview { get; set; }
        public string Homepage { get; set; }

        public string BackdropPath { get; set; }
        public string PosterPath { get; set; }

        public bool Adult { get; set; }

        public List BelongsToCollection { get; set; }
        public List Genres { get; set; }

        public DateTime ReleaseDate { get; set; }
        public long Revenue { get; set; }
        public long Budget { get; set; }
        public int Runtime { get; set; }

        public double Popularity { get; set; }
        public double VoteAverage { get; set; }
        public int VoteCount { get; set; }

        public List ProductionCompanies { get; set; }
        public List ProductionCountries { get; set; }
        public List SpokenLanguages { get; set; }

        public AlternativeTitles AlternativeTitles { get; set; }
        public Releases Releases { get; set; }
        public Casts Casts { get; set; }
        public Images Images { get; set; }
        public KeywordsContainer Keywords { get; set; }
        public Trailers Trailers { get; set; }
        public TranslationsContainer Translations { get; set; }
        public SearchContainer SimilarMovies { get; set; }
        public SearchContainer Lists { get; set; }
        public List Changes { get; set; }

    }

From apiary.io ... Response Body:

{"adult" : false , "backdrop_path" : "/22DQWwjaam1LHTAEapxO2Wg7s2H.jpg" , "belongs_to_collection" : { "id" : 1570 , "name" : "Die Hard Collection" , "poster_path" : "/9RzaUN5E0S6UbXlEVrotKUSMX75.jpg" , "backdrop_path" : "/5kHVblr87FUScuab1PVSsK692IL.jpg" } , "budget" : 92000000 , "genres" : [ { "id" : 28 , "name" : "Action" } , { "id" : 53 , "name" : "Thriller" } ] , "homepage" : "" , "id" : 47964 , "imdb_id" : "tt1606378" , "original_title" : "A Good Day to Die Hard" , "overview" : "Iconoclastic, take-no-prisoners cop John McClane, for the first time, finds himself on foreign soil after traveling to Moscow to help his wayward son Jack - unaware that Jack is really a highly-trained CIA operative out to stop a nuclear weapons heist. With the Russian underworld in pursuit, and battling a countdown to war, the two McClanes discover that their opposing methods make them unstoppable heroes." , "popularity" : 29.1271371554015 , "poster_path" : "/7JKli6FqxK6kEsNRUW8JVGmGSNI.jpg" , "production_companies" : [ { "name" : "20th Century Fox" , "id" : 25 } ] , "production_countries" : [ { "iso_3166_1" : "US" , "name" : "United States of America" } ] , "release_date" : "2013-02-14" , "revenue" : 303725075 , "runtime" : 97 , "spoken_languages" : [ { "iso_639_1" : "en" , "name" : "English" } , { "iso_639_1" : "ru" , "name" : "Pусский" } ] , "status" : "Released" , "tagline" : "Yippee Ki-Yay Mother Russia" , "title" : "A Good Day to Die Hard" , "vote_average" : 5.2 , "vote_count" : 701 }

So for example the "backdrop_path" is giving me "/22DQWwjaam1LHTAEapxO2Wg7s2H.jpg" from apiary.io, but when I deserialize the object with JSON.net it is showing null for that.... as well as a bunch of others.

Thanks!!!

Json.Net uses attributes to serialize/deserialize JSON. Try adding a JsonPropertyAttribute to your properties. This should look something like this:


public class TmdbMovie 
    {
        [JsonProperty( PropertyName = "adult" )]
        public Boolean IsAdult { get; set; }

        [JsonProperty( PropertyName = "backdrop_path" )]
        public String BackdropPath { get; set; }

        [JsonProperty( PropertyName = "belongs_to_collection" )]
        public TmdbBelongsToColelction 

        [JsonProperty( PropertyName = "budget" )]
        public Int64 Budget { get; set; }
}

That makes perfect sense. I've made all the changes, but am now having the following error. I appreciate your help! I'm not sure what to do at this point.

Error: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TMDbLib.Objects.Movies.BelongsToCollection]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path 'belongs_to_collection.id', line 1, position 96.

Here is the BelongsToCollection Class:



    public class BelongsToCollection
    {
        [JsonProperty(PropertyName = "id")]
        public int Id { get; set; }
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
        [JsonProperty(PropertyName = "poster_path")]
        public string PosterPath { get; set; }
        [JsonProperty(PropertyName = "backdrop_path")]
        public string BackdropPath { get; set; }
    }

Well if I understand this correctly, Json.Net throws an error because of it is not able to deserialize the JSON into the specified Type.
As far as I can see, the Problem is that you are trying to deserialize a non-array JSON value into a collection (e.g. List).

Are you sure that Json.Net throws the exception while deserializing BelongsToCollection? Can you post the JSON again?

Btw. This may be useful for you http://json2csharp.com/ (Generates c# classes based on a JSON)

Thanks. I'll look at that website. The reason I thought it had something to do with BelongsToCollection was the last line of the error: "Path 'belongstocollection.id', line 1, position 96." I guess even if I fix that, it may find other problems.

Those error messages are almost always correct… but they are often tricky to understand.

I guess that you have a BelongsToCollection property in your movie class, right?

Is this property of type List or some sort of collection/array?

If yes… you should change the type to just BelongsToCollection (none-collection).

If you post the JSON which you are trying to deserialize, I can maybe give you a more helpful answer.

Alright, I think I've got it fixed, but I'm not sure why :) .... I've removed all of the "[JsonProperty( PropertyName = ... )] lines and have renamed all of the field names (hopefully I've got my programming lingo correct) to match the naming convention of the JSON that is being returned. That seems to map everything properly and I'm not getting any error messages. So for now, I'll say that this has been fixed.

映画やテレビ番組が見つかりませんか?ログインして作成してください。

全般

s 検索バーに移動する
p プロファイルメニューを開く
esc 開いているウィンドウを閉じる
? キーボードショートカットウィンドウを開く

メディアのページ

b 戻る(または該当する場合は親に)
e 編集ページに行く

テレビ番組のシーズンのページ

(右矢印)次のシーズンに行く
(左矢印)前のシーズンに戻る

テレビ番組のエピソードのページ

(右矢印)次のエピソードに進む
(左矢印)前のエピソードに戻る

全ての画像のページ

a 画像追加ウィンドウを開く

全ての編集ページ

t 翻訳選択を開く
ctrl+ s フォームを送信する

ディスカッションのページ

n 新しいディスカッションを作成する
w 監視ステータスを切り替える
p 公開/非公開を切り替える
c 閉じる/開くを切り替える
a アクティビティを開く
r ディスカッションに返信
l 最後の返事に行く
ctrl+ enter メッセージを送信する
(右矢印)次のページ
(左矢印)前のページ

設定

このアイテムを評価したり、リストに追加したりしたいですか?

ログイン

メンバーではありませんか?

登録してコミュニティに参加