【问题标题】:Return List from JSON Url c#从 JSON Url c# 返回列表
【发布时间】:2018-10-29 16:58:21
【问题描述】:

我需要来自 JSON URL 的列表,但我不知道如何从上面的列表中获取这些信息

   ///www.omdbapi.com/
    const string ApiKey = "18693fd6";

    /// <summary>
    /// By Search
    /// www.omdbapi.com/?s=titulo&apikey=18693fd6
    /// </summary>
    /// <param name="filtro"></param>
    /// <returns></returns>
    public List<Film> ListarFilmes(string filtro)
    {

        List<Film> ResultFilm = new List<Film>();

        using (WebClient webClient = new System.Net.WebClient())
        {
            var json = webClient.DownloadString("http://www.omdbapi.com/?s=" + filtro + "&apikey=" + ApiKey);
            dynamic array = JsonConvert.DeserializeObject(json);
            ResultFilm.Add(array) ;
        }

        return ResultFilm;
    }

这是一类电影,我需要在列表中返回标题和年份变量

    public class Film
    {
    /// <summary>
    /// Title
    /// </summary>
    public string Title { get; set; }
    /// <summary>
    /// Year
    /// </summary>
    public int? Year { get; set; }
    }

【问题讨论】:

    标签: c# json arraylist


    【解决方案1】:

    该 json 返回的不仅仅是电影数组。结构如下:

    {
      "Search": [
        {
          "Title": "Sin t\u00c3\u00adtulo (Carta para Serra)",
          "Year": "2011",
          "imdbID": "tt2268553",
          "Type": "movie",
          "Poster": "N\/A"
        },
        {
          "Title": "Pendiente de T\u00c3\u00adtulo",
          "Year": "2008",
          "imdbID": "tt2301959",
          "Type": "series",
          "Poster": "N\/A"
        },
        .....more items here...... 
      ],
      "totalResults": "17",
      "Response": "True"
    }
    

    您需要访问属性Search 以获取电影列表。此代码将为您提供 Film 对象列表,包括标题和年份。

    JToken search = JObject.Parse(json).GetValue("Search");
    ResultFilm = search.Select(f => f.ToObject<Film>()).ToList();
    

    请注意,Json 包含 10 部电影,而不是 totalResults 中所述的 17 部电影。

    【讨论】:

    • 没有填写对象电影的标题和年份字段
    • 这很好用。甚至在我上次编辑之前,它就在检索数据。您需要访问属性“搜索”,否则会引发异常。不能简单地将整个内容解析为 List.
    【解决方案2】:

    你试过了吗?我假设返回的对象只是电影列表

    ResultFilm = JsonConvert.DeserializeObject<List<Film>>(json);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 2020-10-06
      • 2018-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多