Reputation: 351
I am trying to deserialize JSON data coming from Web Api directly .But it is throwinn error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TestMvc.Controllers.HomeController+TestJson]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
My code:
public class TestJson
{
public string thing1
{
get;
set;
}
public string thing2
{
get;
set;
}
}
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://localhost:43560/api/carvalues");
List <TestJson> exam = new List<TestJson>();
exam = JsonConvert.DeserializeObject<List<TestJson>>(json);
}
Sample of json data
{"thing1":"first thing","thing2":"second thing"}
My objective is how can I deserialize the data coming from WebAPI directly. I am using Newtonsoft.Json to deserialize.
Upvotes: 2
Views: 5025
Reputation: 2880
Your JSON data needs to be on array, something like this
"data": [{
"thing1": "first thing",
"thing2": "second thing"
}, {
"thing1": "first thing",
"thing2": "second thing"
}, {
"thing1": "first thing",
"thing2": "second thing"
}]
Or use plain class i.e. particular to this case
exam = JsonConvert.DeserializeObject<TestJson>(json);
Upvotes: 0
Reputation: 24569
In that case use it without list
var exam = new TestJson();
exam = JsonConvert.DeserializeObject<TestJson>(json);
Upvotes: 2
Reputation: 829
Example json data indicates it is just one object coming back in the response where you are expecting array/list of the objects.
Modify the webapi to return list instead of single object and it should fix the issue.
Upvotes: 1