0

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.

Daniel
  • 147
  • 1
  • 7
  • 19
  • 1
    "Id: 1, seems invalid. – Lei Yang Mar 10 '22 at 01:31
  • I have so many questions about this code. 1) Why are you using `.Result` in an `async` method? Why didn't you use `var result = await response.Content.ReadAsStringAsync();`? 2) Why are you parsing the JSON to a JObject, then serializing that back to a JSON string, before then deserializing that to a `List`? What do you feel that this extra step is doing for you? 3) Why do you expect to be able to just deserialize the inner "result" list directly from the containing object's JSON? – ProgrammingLlama Mar 10 '22 at 01:39
  • 2
    I recommend using [this answer](https://stackoverflow.com/a/46825163/3181933) to generate classes to deserialize your JSON to. Also, fix your JSON before you paste it in. – ProgrammingLlama Mar 10 '22 at 01:40

1 Answers1

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; }
}
Serge
  • 40,935
  • 4
  • 18
  • 45