I am trying to consume API receiving JSON objects. The problem is my API sends these objects nested in square brackets, which makes me deseralize it as a List instead of a single object.
I am declaring this variable as an array of this instance of the 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;
}
}
Thiis is a sample of a JSON object I should be receiving, which I tested using 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"
}
]
...And this is 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; }
}
}
I am getting is this error:
JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
How can I deserialize or is something wrong in my code?
CodePudding user response:
you need to fix your 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; }
}