asp.net 将json反序列化对象Map到多模型类

unftdfkk  于 2023-01-22  发布在  .NET
关注(0)|答案(1)|浏览(174)
    • 错误:**

处理请求时发生未经处理的异常。JsonSerializationException:无法将当前JSON对象(例如,{" name ":" value "})反序列化为类型"System. Collections. Generic. List" 1 [Project. Models. Hourly_Units]",因为该类型需要JSON数组(例如,[1,2,3])才能正确反序列化。若要修复此错误,请将JSON更改为JSON数组(例如,[1,2,3]),或者更改反序列化的类型,使其成为可以从JSON对象反序列化的普通. NET类型(例如,不是像整数这样的基元类型,也不是像数组或列表这样的集合类型)。还可以将JsonObjectAttribute添加到该类型中,以强制它从JSON对象反序列化。路径" hourly_units. time",第1行,位置194。

    • 关于项目:**我正在获取json数据,Map到模型类。而不是使用控制器获取json数据并在视图中显示。我可以在View中获取单个值,但在显示List<Hourly_Units>List<Hourly>时出现问题
    • 第2步**-型号分类
public class WeatherModel
{
    public double latitude { get; set; }
    public double longitude { get; set; }
    public double generationtime_ms { get; set; }
    public double utc_offset_seconds { get; set; }
    public string timezone { get; set; }
    public string timezone_abbreviation { get; set; }
    public string elevation { get; set; }
    public List<Hourly_Units> hourly_units { get; set; }
    public List<Hourly> hourly { get; set; }
}

public class Hourly_Units
{
    public string time { get; set; }
    public string temperature_2m { get; set; }
}
public class Hourly
{
    public List<string> time { get; set; }
    public List<double> temperature_2m { get; set; }
}
    • 第3步**-控制器
public async Task<IActionResult> Index()
    {
        //Weather API 
        WeatherModel MyWeatherData = new WeatherModel();
        MyWeatherData = await GetMyWeather();

        return View(MyWeatherData);
    }

    public async Task<WeatherModel> GetMyWeather()
    {
        var latitude = 40.712776;
        var longitude = -74.005974;

        using (var client = new HttpClient())
        {
            try
            {
                client.BaseAddress = new Uri("https://api.open-meteo.com");
                var response = await client.GetAsync($"/v1/forecast?latitude={latitude}&longitude={longitude}&hourly=temperature_2m");
                response.EnsureSuccessStatusCode();

                var stringResult = await response.Content.ReadAsStringAsync(); //get json data in string 
                var rawWeather = JsonConvert.DeserializeObject<WeatherModel>(stringResult); // convert json data into objects

                return rawWeather;

            }
            catch (HttpRequestException httpRequestException)
            {
                throw new Exception($"Error getting weather from OpenWeather: {httpRequestException.Message}");
            }
        }
    }//end of method
    • 第4步**-查看
@model WeatherModel

<form asp-controller="Home" asp-action="Index">
        <button type="submit" class="btn btn-primary">Submit</button>
</form>

<p>latitude: @Model.latitude</p>
<p>longitude: @Model.longitude</p>
<p>generationtime_ms: @Model.generationtime_ms</p>
<p>utc_offset_seconds: @Model.utc_offset_seconds</p>
<p>timezone: @Model.timezone</p>
<p>timezone_abbreviation: @Model.timezone_abbreviation</p>
<p>elevation: @Model.elevation</p>

<p>
    @foreach (var item in Model.hourly_units)
   {
        @Html.DisplayFor(modelItem => item.time)
        @Html.DisplayFor(modelItem => item.temperature_2m)
    }
</p>
<p>
    @foreach (var item in Model.hourly)
    {
        @Html.DisplayFor(modelItem => item.time)
        @Html.DisplayFor(modelItem => item.temperature_2m)
    }
</p>
pod7payv

pod7payv1#

修正模型,你的hourly_units属性不是一个集合,这是一个错误消息

public class WeatherModel
{
    //another properties
    public Hourly_Units hourly_units { get; set; }
    public List<Hourly> hourly { get; set; }
}

public class Hourly
{
    public string time { get; set; }
    public string temperature_2m { get; set; }
}

修正动作代码,解析你的json字符串并转换成新的数据模型

var jObj = JObject.Parse(stringResult);

    var jArr = new JArray();
    for (int i = 0; i < ((JArray)jObj["hourly"]["time"]).Count; i++)
    {
        jArr.Add(new JObject
        {
            ["time"] = (string)((JArray)jObj["hourly"]["time"])[i],
            ["temperature_2m"] = (double)((JArray)jObj["hourly"]["temperature_2m"])[i]
        });
    }
    jObj["hourly"] = jArr;

    var rawWeather = jObj.ToObject<WeatherModel>();

并且也根据新模型来固定视图代码。

相关问题