我正在嘗試使用接收 JSON 物件的 API。問題是我的 API 發送嵌套在方括號中的這些物件,這使我將其反序列化為 List 而不是單個物件。
我將此變數宣告為該類實體的陣列。
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 物件的示例,我使用 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 類:
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 行,位置 0。
我如何反序列化或者我的代碼有問題?
uj5u.com熱心網友回復:
你需要修復你的模型
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; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367031.html
