0

I'm getting json string from webapi like this

{"page":1,"total_results":33,"total_pages":2,"results":
[{"vote_count":8017,"id":603,"video":false,"vote_average":7.9,"title":"The Matrix","popularity":7.82272,"poster_path":"\/lZpWprJqbIFpEV5uoHfoK0KCnTW.jpg","original_language":"en","original_title":"The Matrix","genre_ids":[28,878],"backdrop_path":"\/7u3pxc0K1wx32IleAkLv78MKgrw.jpg","adult":false,"overview":"Set in the 22nd century, The Matrix tells the story of a computer hacker who joins a group of underground insurgents fighting the vast and powerful computers who now rule the earth.","release_date":"1999-03-30"},

{"vote_count":2750,"id":605,"video":false,"vote_average":6.4,"title":"The Matrix Revolutions","popularity":5.073697,"poster_path":"\/sKogjhfs5q3azmpW7DFKKAeLEG8.jpg","original_language":"en","original_title":"The Matrix Revolutions","genre_ids":[12,28,53,878],"backdrop_path":"\/pdVHUsb2eEz9ALNTr6wfRJe5xVa.jpg","adult":false,"overview":"The human city of Zion defends itself against the massive invasion of the machines as Neo fights to end the war at another front while also opposing the rogue Agent Smith.","release_date":"2003-11-05"},
{"vote_count":0,"id":411948,"video":false,"vote_average":0,"title":"Matrix","popularity":1.004394,"poster_path":"\/cseRq8R9RGN66SNUgcD7RJAxBI7.jpg","original_language":"en","original_title":"Matrix","genre_ids":[],"backdrop_path":null,"adult":false,"overview":"John Whitney, Sr. (April 8, 1917 – September 22, 1995) was an American animator, composer and inventor, widely considered to be one of the fathers of computer animation.","release_date":"1971-05-18"}]}

I only want to get title from above string into list.

Here's my code

public List<string> ExtractMoviesList(string movieTitle)
{
    using (var client = new HttpClient())
    {
        // HTTP GET
        var response = client.GetAsync(string.Format("{0}{1}", movies_Url, movieTitle)).Result;

        using (HttpContent content = response.Content)
        {                
            var json = content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result);

            return result.Select(p=>p.Title).ToList();                     
        }
    }            
}

There's something wrong with this line of code: var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result); after this line executed the var result is getting just null.

1
  • There's something wrong with this line of code. var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result); after this line executed the var result is getting just null. Commented Jul 13, 2017 at 21:21

1 Answer 1

1

Your problem is that you are trying to deserialize your JSON as a List<T>, but the root object in your JSON is not an array, it's an object. This is easy to see if you format and indent your JSON using, say, https://jsonformatter.curiousconcept.com/:

{
   "page":1,
   "total_results":33,
   "total_pages":2,
   "results":[
      {
         "title":"The Matrix",
          // Other fields
      },
      // Other movies
   ]
}

The data model to which you are binding your JSON must reflect this outer container object for deserialization to succeed. Luckily http://json2csharp.com/ or Paste JSON as Classes will generate one for you:

public class Movie
{
    public string title { get; set; }
    public int vote_count { get; set; }
    public int id { get; set; }
    public bool video { get; set; }
    public double vote_average { get; set; }
    public double popularity { get; set; }
    public string poster_path { get; set; }
    public string original_language { get; set; }
    public string original_title { get; set; }
    public List<object> genre_ids { get; set; }
    public string backdrop_path { get; set; }
    public bool adult { get; set; }
    public string overview { get; set; }
    public string release_date { get; set; }
}

public class RootObject
{
    public int page { get; set; }
    public int total_results { get; set; }
    public int total_pages { get; set; }
    public List<Movie> results { get; set; }
}

Now you can do:

var result = JsonConvert.DeserializeObject<RootObject>(json.Result);
return result.results.Select(m => m.title).ToList();

Incidentally, if you don't want to create a data model just to extract the titles from this JSON, you can use Json.NET's LINQ to JSON functionality to load and query the JSON directly:

var result = JToken.Parse(json.Result);
return result.SelectTokens("results[*].title").Select(t => (string)t).ToList();

Here I am using SelectTokens() with the JsonPATH wildcard operator [*] to find all entries in the results array.

Working .Net fiddle showing both options.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks dbc for your help. It works and good explanation of everything.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.