簡體   English   中英

ASP.NET MVC 核心消耗 Web API 與 Arrays?

[英]ASP.NET MVC Core Consuming Web API with Arrays?

我遇到了困難,雖然我徹底(我認為)研究了 web,包括在 SO 處,但我似乎找不到我要找的東西——或者我很遲鈍。 我的環境是.NET6,ASP.NET Core MVC。

從我的 API 成功獲取 Json 后,我遇到的錯誤是:

JsonSerializationException:無法將當前的 JSON object(例如 {"name":"value"})反序列化為類型 'System.Collections.Generic.List`1[ConsumeWebApi.Models.Weather+Root]' 因為該類型需要一個 JSON 數組(例如 [1,2,3]) 以正確反序列化。 要修復此錯誤,請將 JSON 更改為 JSON 數組(例如 [1,2,3])或更改反序列化類型,使其成為正常的 .NET 類型(例如,不是像 integer 這樣的原始類型,不是像數組或列表),可以從 JSON object 反序列化。也可以將 JsonObjectAttribute 添加到類型以強制它從 JSON object 反序列化。路徑“區域”,第 1 行,position 10。

這對我來說似乎很簡單,所以我檢查了返回的字符串。

{
    "region": "My Town, ST",
    "currentConditions": {
        "dayhour": "Tuesday 9:00 AM",
        "temp": {
            "c": 14,
            "f": 58
        },
        "precip": "15%",
        "humidity": "72%",
        "wind": {
            "km": 3,
            "mile": 2
        },
        "iconURL": "https://ssl.gstatic.com/onebox/weather/64/sunny.png",
        "comment": "Sunny"
    },
    "next_days": [
        {
            "day": "Tuesday",
            "comment": "Scattered showers",
            "max_temp": {
                "c": 24,
                "f": 75
            },
            "min_temp": {
                "c": 14,
                "f": 58
            },
            "iconURL": "https://ssl.gstatic.com/onebox/weather/48/rain_s_cloudy.png"
        },
        {
            "day": "Wednesday",
            "comment": "Scattered showers",
            "max_temp": {
                "c": 17,
                "f": 62
            },
            "min_temp": {
                "c": 9,
                "f": 49
            },
            "iconURL": "https://ssl.gstatic.com/onebox/weather/48/rain_s_cloudy.png"
        },
        {
            "day": "Thursday",
            "comment": "Mostly cloudy",
            "max_temp": {
                "c": 22,
                "f": 71
            },
            "min_temp": {
                "c": 12,
                "f": 54
            },
            "iconURL": "https://ssl.gstatic.com/onebox/weather/48/partly_cloudy.png"
        },
        {
            "day": "Friday",
            "comment": "Rain",
            "max_temp": {
                "c": 17,
                "f": 62
            },
            "min_temp": {
                "c": 12,
                "f": 53
            },
            "iconURL": "https://ssl.gstatic.com/onebox/weather/48/rain.png"
        },
        {
            "day": "Saturday",
            "comment": "Showers",
            "max_temp": {
                "c": 16,
                "f": 60
            },
            "min_temp": {
                "c": 8,
                "f": 46
            },
            "iconURL": "https://ssl.gstatic.com/onebox/weather/48/rain_light.png"
        },
        {
            "day": "Sunday",
            "comment": "Partly cloudy",
            "max_temp": {
                "c": 19,
                "f": 66
            },
            "min_temp": {
                "c": 7,
                "f": 45
            },
            "iconURL": "https://ssl.gstatic.com/onebox/weather/48/partly_cloudy.png"
        },
        {
            "day": "Monday",
            "comment": "Partly cloudy",
            "max_temp": {
                "c": 22,
                "f": 72
            },
            "min_temp": {
                "c": 9,
                "f": 48
            },
            "iconURL": "https://ssl.gstatic.com/onebox/weather/48/partly_cloudy.png"
        },
        {
            "day": "Tuesday",
            "comment": "Mostly sunny",
            "max_temp": {
                "c": 26,
                "f": 79
            },
            "min_temp": {
                "c": 13,
                "f": 55
            },
            "iconURL": "https://ssl.gstatic.com/onebox/weather/48/partly_cloudy.png"
        }
    ],
    "contact_author": {
        "email": "communication.with.users@gmail.com",
        "auth_note": "Mail me for feature requests, improvement, bug, help, ect... Please tell me if you want me to provide any other free easy-to-use API services"
    },
    "data_source": "https://www.google.com/search?lr=lang_en&q=weather+in+mycity+state"
}

我看到的唯一數組是“next_days”,但正如您在下面的數據 model 中看到的那樣,我對此進行了說明。 我的 model 是由 Visual Studio 中的“將 Json 粘貼為類”功能創建的,它是:

namespace ConsumeWebApi.Models
{
    public class Weather
    {

        public class Root
        {
            public string? Region { get; set; }
            public Currentconditions? CurrentConditions { get; set; }
            public Next_Days[]? Next_days { get; set; }
            public Contact_Author? Contact_author { get; set; }
            public string? Data_source { get; set; }
        }

        public class Currentconditions
        {
            public string? Dayhour { get; set; }
            public Temp? Temp { get; set; }
            public string? Precip { get; set; }
            public string? Humidity { get; set; }
            public Wind? Wind { get; set; }
            public string? IconURL { get; set; }
            public string? Comment { get; set; }
        }

        public class Temp
        {
            public int? C { get; set; }
            public int? F { get; set; }
        }

        public class Wind
        {
            public int? Km { get; set; }
            public int? Mile { get; set; }
        }

        public class Contact_Author
        {
            public string? Email { get; set; }
            public string? Auth_note { get; set; }
        }

        public class Next_Days
        {
            public string? Day { get; set; }
            public string? Comment { get; set; }
            public Max_Temp? Max_temp { get; set; }
            public Min_Temp? Min_temp { get; set; }
            public string? IconURL { get; set; }
        }

        public class Max_Temp
        {
            public int? C { get; set; }
            public int? F { get; set; }
        }

        public class Min_Temp
        {
            public int? C { get; set; }
            public int? F { get; set; }
        }


    }
}

讓我們看看我的 controller。(這是我懷疑我不太明白的地方。這里或我的 model。)

        public async Task<IActionResult> Index()
        {
            List<Weather.Root> weatherInfo = new List<Weather.Root>();
            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync("https://weatherdbi.herokuapp.com/data/weather/mycity+state"))
                {
                    string? apiResponse = await response.Content.ReadAsStringAsync();
                    weatherInfo = JsonConvert.DeserializeObject<List<Weather.Root>>(apiResponse);
                }
            }
            return View(weatherInfo);
        }

在 Visual Studio 中調試顯示 apiResponse 具有我在上面發布的 Json 數據 - 沒有找到額外的方括號 []。

對於這個基本問題,我深表歉意,並提前感謝您的回復。 我是 C# 的新手,但不是 web 開發的新手。

Root是一個object,不是集合。 所以只使用這段代碼

 weatherInfo = JsonConvert.DeserializeObject<Weather.Root>(apiResponse);

要解決“無法反序列化當前 JSON 數組(例如 [1,2,3])”,請按照以下步驟操作:

  1. 使用在線轉換器將 JSON 轉換為 C#(例如https://json2csharp.com/ )。
  2. 將您的 JSON 粘貼到 JSON 部分並生成 C#。
  3. 它將生成代碼並為您提供反序列化的方法。 例如 JsonDataService myData = JsonConvert.DeserializeObject(JSON); //JSON解析

暫無
暫無

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

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