代码之家  ›  专栏  ›  技术社区  ›  Baxorr

C#.net http |如何从API获取对象层

  •  0
  • Baxorr  · 技术社区  · 5 年前

    "Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Dashboard.Weather' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly."
    

    感谢您的帮助,我正在努力天气.描述“,下面是我的示例代码:

    public class Weather
    {
        public string Description{ get; set; }
    }
    
    public class Product
    {
        public Weather Weather { get; set; }
    }
    
    public static class ApiHelper
    {
        static string city_id = "CITY_ID";
        static string api_key = "API_KEY";
        public static HttpClient client = new HttpClient();
    
        public static void InitializeClient()
        {
            client.BaseAddress = new Uri($"http://api.openweathermap.org/data/2.5/weather?id={city_id}&APPID={api_key}");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }
    
        public static async Task<Weather> GetProductAsync()
        {
            Product product = null;
            HttpResponseMessage response = await client.GetAsync("");
            if (response.IsSuccessStatusCode)
            {
                product = await response.Content.ReadAsAsync<Product>();
            }
            return product.Weather;
    
        }
    }
    
        async void SetLabelText()
        {
            var weather = await ApiHelper.GetProductAsync();
    
            descriptionLabel.Text = $"Description: {weather.Description}";
        }
    

    API的响应格式如下

    {"coord":{"lon":-89.59,"lat":41.56},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":279.27,"feels_like":275.4,"temp_min":278.15,"temp_max":280.37,"pressure":1027,"humidity":74},"visibility":16093,"wind":{"speed":3.1,"deg":200},"clouds":{"all":1},"dt":1576951484,"sys":{"type":1,"id":3561,"country":"US","sunrise":1576934493,"sunset":1576967469},"timezone":-21600,"id":4915397,"name":"Walnut","cod":200}
    
    0 回复  |  直到 5 年前
        1
  •  2
  •   Bill Keller    5 年前

    你的 Product 模型与您接收的json不正确对齐。

    您发布的json将天气作为一个列表,但是

    解决方法应该很简单; Product.Weather 应为类型 List<Weather> IEnumerable<Weather> Weather[]