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!
Can't find a movie or TV show? Login to create it.
Want to rate or add this item to a list?
Not a member?
Reply by tmdb78260312
on June 24, 2013 at 5:47 AM
Can you post your Movie class and the JSON returned by the TMDb API?
Reply by Mark Terborg
on June 24, 2013 at 10:12 AM
Here is my Movie class:
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!!!
Reply by tmdb78260312
on June 24, 2013 at 10:28 AM
Json.Net uses attributes to serialize/deserialize JSON. Try adding a JsonPropertyAttribute to your properties. This should look something like this:
Reply by Mark Terborg
on June 24, 2013 at 2:55 PM
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:
Reply by tmdb78260312
on June 25, 2013 at 1:00 AM
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)
Reply by Mark Terborg
on June 25, 2013 at 12:26 PM
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.
Reply by tmdb78260312
on June 25, 2013 at 12:56 PM
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.
Reply by Mark Terborg
on June 25, 2013 at 1:57 PM
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.