Search code examples
c#asp.net-mvc-5

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'portal.Models.SubProjectViewRecord'


I've got this simple code that will consume api json array from a url.

public ActionResult ViewRecord()
        {

            ViewBag.Title = "- Geotagging Sub Project Record.";
            var webClient = new WebClient();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                     | SecurityProtocolType.Tls11
                                     | SecurityProtocolType.Tls12;
            webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
            string objJson = webClient.DownloadString(@"https://test.com/api/lib_region");

             //here we will map the Json to C# class
            Models.SubProjectViewRecord oop = JsonConvert.DeserializeObject<Models.SubProjectViewRecord>(objJson);                                                                                                               
            return View(oop);
            
    }

my model

namespace portal.Models
{
    public class SubProjectViewRecord
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }
}

The error of the code above is:

'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'portal.Models.SubProjectViewRecord' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.'

then these are the fixes I apply to model as some reply being posted.

public class SubProjectViewRecord
        {
            public List<string> Name { get; set; }
            public List<int> Id { get; set; }
        }

to this line:

Models.SubProjectViewRecord oop = JsonConvert.DeserializeObject<List<Models.SubProjectViewRecord>>(objJson);

but the error raised:

Cannot implicitly convert type 'System.Collections.Generic.List<portal.Models.SubProjectViewRecord>' to 'portal.Models.SubProjectViewRecord'

Solution

  • Apparently looks like from the error that there are multiple items in the array that is why there is any array returned from the api reponse. you can use a List<T> for it and the code for it would be like :

    List<Models.SubProjectViewRecord> oop = JsonConvert.DeserializeObject<List<Models.SubProjectViewRecord>>(objJson);
    

    While your model would be below assuming that the json array elements are of json object with Id and Name members in it:

    public class SubProjectViewRecord
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }