[英]Deserialize a JSON object Inside of an Array/Square brackets
我正在尝试使用 API 接收 JSON 对象。 问题是我的 API 将这些对象嵌套在方括号中,这使我将其反序列化为列表而不是单个 object。
我将此变量声明为该 class 实例的数组。
SomeModel[] variable = new SomeModel[1];
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://someurl.dev.local/getInfo/" + id))
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string apiResponse = await response.Content.ReadAsStringAsync();
variable = JsonConvert.DeserializeObject<SomeModel[]>(apiResponse);
}
else
ViewBag.StatusCode = response.StatusCode;
}
}
这是我应该收到的 JSON object 的样本,我使用 Postman 进行了测试:
[
{
"pri_key": "7005210446", //concatenation of this_nbr & that_nbr
"dl_load_date": "2021-11-25T00:00:00Z",
"this_nbr": 7005210,
"that_nbr": 446,
"Passtest": "Eligible"
}
]
...这是SomeModel class:
namespace ThisSolution.Models
{
public partial class SomeModel
{
public DateTime? DlLoadDate { get; set; }
public int? ThisNbr{ get; set; }
public int? ThatNbr { get; set; }
public string Passtest { get; set; }
public string PriKey { get; set; }
}
}
我得到的是这个错误:
JsonReaderException:解析值时遇到意外字符:<。 路径'',第 0 行,position 0。
如何反序列化或我的代码有问题?
你需要修复你的 model
public partial class SomeModel
{
[JsonProperty("pri_key")]
public string PriKey { get; set; }
[JsonProperty("dl_load_date")]
public DateTimeOffset DlLoadDate { get; set; }
[JsonProperty("this_nbr")]
public int? ThisNbr { get; set; }
[JsonProperty("that_nbr")]
public int? ThatNbr { get; set; }
[JsonProperty("Passtest")]
public string Passtest { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.