首页 > 解决方案 > 将 JSON 中的数组转换为列表

问题描述

您好,这是我的 JSON 服务器:

http://api.tvmaze.com/search/shows?q=boys

我使用 REST API 根据我想从 JSON 获取的数据创建一个新列表,这是我创建的类:

public class TVMazeModel
{
    public Show show { get; set; }
    public Rating rating { get; set; }
    public Image image { get; set; }
}

public class Show
{
    public int id { get; set; }
    public string url { get; set; }
    public string name { get; set; }
}

public class Rating
{
    public decimal average { get; set; }
}

public class Image
{
    public string original { get; set; }
}

和 TVMazeController :

[HttpGet]
[Route("{searchText}")]
public IActionResult GetProductsExpensiveThan(string searchText)
{
    try
    {
        var json = new WebClient().DownloadString("http://api.tvmaze.com/search/shows?q=" + searchText);

        var objResponse1 = JsonConvert.DeserializeObject<List<TVMazeModel>>(json);

        var json2 = new JavaScriptSerializer().Serialize(objResponse1);
        return Ok(json2);
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
    }
}

当我运行服务器端并在 Internet 中浏览时:https://localhost:44395/api/TVMaze/boys

这就是我得到的:

com/shows/1522/mrs-browns-boys","name":"Mrs. 布朗男孩"},"rating":null,"image":null},{"show":{"id":1265,"url":"http://www.tvmaze.com/shows/1265/angry -boys","name":"愤怒的男孩"},"rating":null,"image":null}]

那么为什么 rating 是 null 而 image 是 null 呢?

节目的部分效果很好,只是他们有问题..

我想像我上面写的类一样获得 rating.average 和 image.original ...

标签: c#rest

解决方案


根据我从https://api.tvmaze.com/search/shows?q=a得到的回复,我意识到 Image 和 Rating 落后于 show,因此您必须创建与第三个结构相同的 TVMazeModel网址响应。

尝试这个:

    public class TVMazeModel
    {
        public Show show { get; set; }   
    }
    
    public class Show
    {
        public int id { get; set; }
        public string url { get; set; }
        public string name { get; set; }
        public Rating rating { get; set; }
        public Image image { get; set; }
    }
    public class Rating
    {
        public decimal average { get; set; }
    }

    public class Image
    {
        public string original { get; set; }
    }

推荐阅读