简体   繁体   English

将反序列化JSON对象放入列表C#

[英]get deserialize json objects into list c#

I'm getting json string from webapi like this 我从这样的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"}]}

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); 这行代码出了点问题: var result = JsonConvert.DeserializeObject<List<Movies>>(json.Result); after this line executed the var result is getting just null. 在这一行执行后,var结果只是空。

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. 您的问题是您尝试将JSON反序列化为List<T> ,但是JSON中的根对象不是数组,而是一个对象。 This is easy to see if you format and indent your JSON using, say, https://jsonformatter.curiousconcept.com/ : 很容易看出您是否使用https://jsonformatter.curiousconcept.com/格式化和缩进JSON:

{
   "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. 绑定JSON的数据模型必须反映此外部容器对象,以便反序列化成功。 Luckily http://json2csharp.com/ or Paste JSON as Classes will generate one for you: 幸运的是, http://json2csharp.com/粘贴JSON作为类将为您生成一个:

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: 顺便说一句,如果您不想创建数据模型只是为了从此JSON中提取标题,则可以使用Json.NET的LINQ to JSON功能直接加载和查询JSON:

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. 在这里,我使用带有JsonPATH通配符[*] SelectTokens()来查找results数组中的所有条目。

Working .Net fiddle showing both options. 可以显示两种选择的工作.Net小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM