'How to get an array inside a JSON response in .NET Core?
I working with a JSON that has this form:
{
"success": true,
"message": "OK!",
"result": [
{
"Id": 1,
"description": "Creacion",
"name": "name1"
},
{
"Id": 1,
"description": "Creacion",
"name": "name2"
}
]
}
I want to get the result array data. I've trying with this:
List<object> list = new List<object>();
public async Task<bool> GetList()
{
JObject json = new JObject();
HttpClient http = new HttpClient();
string urlComplete = "https://..."; // url where the data is obtained
var response = await http.GetAsync(urlComplete);
var result = response.Content.ReadAsStringAsync().Result;
json = JObject.Parse(result);
ContractStateList = JsonConvert.DeserializeObject<List<object>>(json.ToString());
return true;
}
But it throws an error that says Cannot deserialize the current JSON object...
Any help is appreciated.
Solution 1:[1]
you have to add to headers a content type that shoult be returned. Try this code
public async Task<List<Result>> GetList()
{
using (var client = new HttpClient())
{
var urlAddress = "http://...";
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
var response = await client.GetAsync(urlAddress);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var jsonParsed=JObject.Parse(json);
var jsonResult=jsonParsed["result"];
if (jsonResult!=null)
{
List<Result> result = jsonResult.ToObject<List<Result>>();
return result;
}
}
}
return null;
}
and create class
public partial class Result
{
[JsonProperty("Id")]
public long Id { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
