skip to Main Content

I have models

public class MainResponse
{
    public bool IsSuccess { get; set; }
    public string? ErrorMessage { get; set; }
    public object? Content { get; set; }
}

public class Person
{
    public int Id { get; set; }
    public string? Firstname { get; set; }
    public string? Lastname{ get; set; }
}

I am using API to get data from database.

My Json is

{
  "IsSuccess": true,
  "ErrorMessage": null,
  "Content": [
    {
      "Id": 1,
      "Firstname": "John",
      "Lastname": "Poly"
    }
  ]
}

I tried to deserialize Json:

HttpResponseMessage response = await client.GetAsync("https://localhost:7134/api/Person/GetAll");
string jsonResponse = await response.Content.ReadAsStringAsync();

Person p = JsonConvert.DeserializeObject<Person>(json);

I am not able to get data from Json to my model Person.

2

Answers


  1. Chosen as BEST ANSWER

    Sorry, I made mistake is supposed to be

    Person p = JsonConvert.DeserializeObject<Person>(jsonResponse);
    

    as you said but I got all null in p object


  2. You need to deserialise MainResponse first and then get a list of Person from the Content property.

    Unfortunately it also not possible to convert object? to Person[] either and the response appears to be a list of Person but that can be remedied with generics.

    public class MainResponse<TContent>
    {
        public bool IsSuccess { get; set; }
        public string? ErrorMessage { get; set; }
        public TContent Content { get; set; }
    }
    

    You can now deserialise this properly… Notice that we also use the correct variable name jsonResponse too.

    HttpResponseMessage response = await client.GetAsync("https://localhost:7134/api/Person/GetAll");
    string jsonResponse = await response.Content.ReadAsStringAsync();
    
    MainResponse response = JsonConvert.DeserializeObject<MainResponse<Person[]>(jsonResponse);
    
    Person[] people = response.Content;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search