簡體   English   中英

將反序列化JSON對象放入列表C#

[英]get deserialize json objects into list c#

我從這樣的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結果只是空。

您的問題是您嘗試將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/粘貼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; }
}

現在您可以執行以下操作:

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

在這里,我使用帶有JsonPATH通配符[*] SelectTokens()來查找results數組中的所有條目。

可以顯示兩種選擇的工作.Net小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM