Reputation: 15
Where I am missing info? I need to deserialize the following JSON string.
{
"data": [
{
"FirstName": "Test",
"LastName": "Test"
}
]
}
For this, I have defined my LoadData Action Method:
public async Task<ActionResult> LoadData()
{
string apiUrl = "URL";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var input = new { depot = "DATA", fromDate = "2020-06-06", toDate = "2020-06-06" };
var response1 = await client.PostAsJsonAsync("DATAOne", input);
if (response1.IsSuccessStatusCode)
{
var data = await response1.Content.ReadAsStringAsync();
var table = JsonConvert.DeserializeObject<List<PartOne>>(data);
}
}
return View();
}
For this, I have defined my class:
public class PartOne
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
But when I try using the de-serializer, it gives an exception.
{"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) 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 2, position 12."}
Upvotes: 1
Views: 1909
Reputation: 3499
You have two options here:
1st Option, you are missing a wrapper object for data
public class Wrapper<T>
{
public T Data { get; set; }
}
and then use:
var table = JsonConvert.DeserializeObject<Wrapper<List<PartOne>>>(json).Data;
2nd Option, deserialize it first as JObject and access to data and then deserialize it to the List<PartOne>
:
var jObj = JsonConvert.DeserializeObject(json) as JObject;
var jArr = jObj.GetValue("data");
var table = jArr.ToObject<List<PartOne>>();
Upvotes: 2