C# 错误mvc.net core无法使用api调用反序列化当前JSON对象
我有一个对IExtradingAPI进行get调用的应用程序。调用本身返回数据,但当我想将其加载到viewmodel中以显示数据时,它会返回一条错误消息“无法反序列化当前JSON对象”。我已经创建了一个单独的viewmodel,数据应该加载到其中 我的控制器C# 错误mvc.net core无法使用api调用反序列化当前JSON对象,c#,asp.net-mvc,rest,.net-core,httprequest,C#,Asp.net Mvc,Rest,.net Core,Httprequest,我有一个对IExtradingAPI进行get调用的应用程序。调用本身返回数据,但当我想将其加载到viewmodel中以显示数据时,它会返回一条错误消息“无法反序列化当前JSON对象”。我已经创建了一个单独的viewmodel,数据应该加载到其中 我的控制器 using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Acce
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://cloud.iexapis.com/");
HttpResponseMessage response = client.GetAsync($"stable/stock/aapl/quote?filter=symbol,companyName,volume,latestSource,latestPrice,latestTime&token=MY_KEY").Result;
var resultList = response.Content.ReadAsAsync<List<GetQuoteAPIViewModel>>().GetAwaiter().GetResult();
}
return View(resultList);
}
我的看法是:
@model WebApplication1.Models.ViewModels.GetQuoteAPIViewModel
@{
ViewData["Title"] = "Home Page";
}
<div>
@foreach(var quote in Model)
{
@quote.latestPrice
@quote.LatestTime
@($"{quote.symbol}, {quote.companyName}")
@quote.latestSource
}
</div>
@model WebApplication1.Models.ViewModels.getQuoteAppiviewModel
@{
ViewData[“Title”]=“主页”;
}
@foreach(模型中的var报价)
{
@最新价格
@最新报价
@($“{quote.symbol},{quote.companyName}”)
@quote.latestSource
}
很明显,我缺少了一些东西,比如转换到特定类型。但是,如果我直接使用模型,然后使用varresultList=response.Content.ReadAsAsync().GetAwaiter().GetResult()代码>将数据加载到我的视图中。问题似乎是我不能使用索引或枚举,因为它没有枚举器。
解决这个问题的典型.net核心MVC方法是什么,包括viewmodels等?JSON是什么样子的?您的视图是什么样子的?您是否继承了GetQuoteAppiviewModel?@user10728126我添加了我的视图,包括我要创建的模型using@GaryStewart如果我使用response.Content.ReadAsStringAsync().Result;我得到一个返回的json对象{“symbol”:“BAC”,“companyName”:“Bank of America Corp.”,“volume”:null,“latestSource”:“Close”,“latestPrice”:27.05,“latestTime”:“2019年9月3日”}。这就是你的意思吗?@CMorgan是的,所以JSON结果似乎没有“ApiQuote”的集合,它是一个ApiQuote。JSON看起来像什么?你的视图看起来像什么?您是否继承了GetQuoteAppiviewModel?@user10728126我添加了我的视图,包括我要创建的模型using@GaryStewart如果我使用response.Content.ReadAsStringAsync().Result;我得到一个返回的json对象{“symbol”:“BAC”,“companyName”:“Bank of America Corp.”,“volume”:null,“latestSource”:“Close”,“latestPrice”:27.05,“latestTime”:“2019年9月3日”}。这就是你的意思吗?@CMorgan是的,所以JSON结果似乎没有“ApiQuote”的集合,它是一个ApiQuote。。
public class ApiQuote
{
public string symbol { get; set; }
public string companyName { get; set; }
public string LatestTime { get; set; }
public string latestSource { get; set; }
public int iexVolume { get; set; }
public decimal latestPrice { get; set; }
public System.Net.HttpStatusCode IsSuccessStatusCode { get; set; }
}
}
@model WebApplication1.Models.ViewModels.GetQuoteAPIViewModel
@{
ViewData["Title"] = "Home Page";
}
<div>
@foreach(var quote in Model)
{
@quote.latestPrice
@quote.LatestTime
@($"{quote.symbol}, {quote.companyName}")
@quote.latestSource
}
</div>