My Goal: I want to store the response I get from an API into a self-defined object (ABCResponse).
Problem: I encountered the error: "Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly"
Details: I have created ABIResponse object to match the different fields in the JSON.
public class ABCResponse
{
public string Code { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Id { get; set; }
public string Code { get; set; }
public string Message { get; set; }
}
My code is below.
public async Task<ABCResponse> CreateABIProject(ABCProjectDto project) {
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.ConnectionClose = true;
var authenticationString = $"{username}:{password}";
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationString);
HttpResponseMessage response = await client.PostAsJsonAsync(url,project);
var responseContent = await response.Content.ReadAsStringAsync();
var abcResponse = JsonConvert.DeserializeObject<ABCResponse>(responseContent);
return abcResponse;
}
the CreateABCProject is used in the below line:
var status = await abcConnector.CreateABCProject(project);
in which I will need to retrieve the response using status.Code
My question: Is it that I am not supposed to use JsonConvert.DeserializeObject?
Thank you in advance.