user2465036 user2465036 - 3 months ago 16
JSON Question

How to deserialize json data coming from web api directly

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.

Answer

In that case use it without list

var exam = new TestJson();    
exam = JsonConvert.DeserializeObject<TestJson>(json);
Comments