Question Cannot deserialize the current because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly

Anonymous

Well-known member
Joined
Sep 29, 2020
Messages
84
Programming Experience
Beginner
Hello,

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:
Code doesn 't reflect the JSON. The JSON response is an object with two props, message and data. Your code is essentially missing this layer, and seemingly is trying to map a array of Response classes to just the object (not an array) json inside the "data" prop


The easier way:

* Go to Instantly parse JSON in any language | quicktype
* Paste JSON in, choose NewtonSoft or STJ, set options like C#, choose namespace etc
* Use Nuget to install Flurl.Http
* Have a code like:

C#:
        private async void button1_Click(object sender, EventArgs e)
        {
            await APIAsync();
        }
        private async Task APIAsync()
        {
            try
            {
                var r = the_name_you_chose_on_quicktype.FromJson(await "https://97mm2.sse.codesandbox.io/teachers/200".GetStringAsync());

                //use r?
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

If the JSON is simple and doesn't need the converters QT made for you, you can even use:

C#:
await "https://97mm2.sse.codesandbox.io/teachers/200".GetJsonAsync<the_name_you_chose_on_quicktype>();
 
Last edited:

Latest posts

Back
Top Bottom