Hello,
I am using the following test API -
I am getting the response but when I am trying to deserialize it, I am getting the following error -
My code is :
I am using the following test API -
JSON:
{
"message":"Required Teacher",
"data":{
"id":200,
"firstName":"Jerold",
"lastName":"Britto",
"age":28,
"email":"britto@xyz.com",
"class":10,
"students":[
{
"studentid":1,
"firstName":"Ajay",
"lastName":"Vignesh",
"age":22,
"gender":"male"
},
{
"studentid":2,
"firstName":"Lakshman",
"lastName":"kumar",
"age":22,
"gender":"male"
}
]
}
}
I am getting the response but when I am trying to deserialize it, I am getting the following error -
C#:
{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[InfluxDB.Serie]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'results', line 1, position 11."}
My code is :
C#:
public class Response
{
public int id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public int age { get; set; }
public string email { get; set; }
public List<Student> students { get; set; }
}
public class Student
{
public int studentid { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public int age { get; set; }
public string gender { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
APIAsync();
}
private async Task APIAsync()
{
try
{
var baseAddress = "https://97mm2.sse.codesandbox.io/teachers/200";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(baseAddress).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Request Message Information:- \n\n" + response.RequestMessage + "\n");
Console.WriteLine("Response Message Header \n\n" + response.Content.Headers + "\n");
// Get the response
var teacherJsonString = await response.Content.ReadAsStringAsync();
Console.WriteLine("Your response data is: " + teacherJsonString);
// Deserialise the data (include the Newtonsoft JSON Nuget package if you don't already have it)
var deserialized = JsonConvert.DeserializeObject<IEnumerable<Response>>(teacherJsonString);
// Do something with it
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Last edited by a moderator: