【问题标题】:Storing JSON REST response in object在对象中存储 JSON REST 响应
【发布时间】:2014-11-26 04:55:00
【问题描述】:

我是C# 的新手,我正在尝试研究如何将我的HTTPResponseMessage 存储在一个对象中。

static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://api.themoviedb.org/3/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("search/tv?api_key=MY_KEYa&query=hawaii%20five%20o&first_air_date_year=2010");                

            if (response.IsSuccessStatusCode)
            {


                // What to do here..?


            }
        }
    }

我使用这个网站 (http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client) 来编写上面的代码。

使用这个网站 (http://json2csharp.com/),我创建了以下类:

class TVShowDTO
{
    public string backdrop_path { get; set; }
    public int id { get; set; }
    public string original_name { get; set; }
    public string first_air_date { get; set; }
    public List<string> origin_country { get; set; }
    public string poster_path { get; set; }
    public double popularity { get; set; }
    public string name { get; set; }
    public int vote_average { get; set; }
    public int vote_count { get; set; }
}

API 响应:

{
   page: 1
   results: [1]
   0:  {
   backdrop_path: "/mAXpHFDTMHvJt7WdibFWdbRsdCG.jpg"
   id: 32798
   original_name: "Hawaii Five-0"
   first_air_date: "2010-09-20"
   origin_country: [1]
   0:  "US"
   -
   poster_path: "/hO4BgEJhGIrFJ7f00sR6ZcdNB6y.jpg"
   popularity: 1.06099324148627
   name: "Hawaii Five-0"
   vote_average: 7.3
   vote_count: 6
   }-
   -
   total_pages: 1
   total_results: 1
}

这是我正在尝试访问的API 的链接:http://docs.themoviedb.apiary.io/reference/search/searchtv/get

我需要先将response 作为string 吗?因为我在 SO 上看到的示例似乎使用了输入 string

我无法解决这个问题,因为当我打印 response.Content 时,它只会返回 "System.Net.Http.StreamContent"

我们将不胜感激。

【问题讨论】:

    标签: c# json rest themoviedb-api


    【解决方案1】:

    首先,您需要获取响应字符串:

    string responseContent = await response.Content.ReadAsStringAsync();
    

    然后,您可以使用来自 NUGET 的 Json.NET 之类的工具反序列化为您的对象:

    var obj = JsonConvert.DeserializeObject<TVShowDTO>(responseContent);
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 2019-11-10
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多