将json对象反序列化为列表c#

时间:2017-07-13 21:02:49

标签: c# json asp.net-web-api

我从这个

获取webapi的json字符串
{"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"}]}

我只想从上面的字符串中获取标题。

这是我的代码

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();                     
        }
    }            
}

这行代码有问题:var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result);执行此行后,var结果只是为空。

1 个答案:

答案 0 :(得分:1)

您的问题是您尝试将JSON反序列化为List<T>,但JSON中的根对象不是数组,而是一个对象。如果您使用https://jsonformatter.curiousconcept.com/

格式化并缩进JSON,则很容易看到
{
   "page":1,
   "total_results":33,
   "total_pages":2,
   "results":[
      {
         "title":"The Matrix",
          // Other fields
      },
      // Other movies
   ]
}

绑定JSON的数据模型必须反映此外部容器对象才能成功进行反序列化。幸运的是,http://json2csharp.com/Paste JSON as Classes会为您生成一个:

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; }
}

现在你可以做到:

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

顺便提一下,如果您不想创建数据模型只是为了从这个JSON中提取标题,您可以使用Json.NET的LINQ to JSON功能直接加载和查询JSON:

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

这里我使用SelectTokens()JsonPATH通配符运算符[*]来查找results数组中的所有条目。

工作.Net fiddle显示两个选项。