[SOLVED] deserialize a Json using a Response

Issue

I am trying to deserialize a response delivered by an API in my Xamarin application as follows:

 public async Task<Response> RegisterUserAsync(string urlBase, string servicePrefix, string controller, UserRequest userRequest)
        {
            try
            {
                string request = JsonConvert.SerializeObject(userRequest);
                StringContent content = new StringContent(request, Encoding.UTF8, "application/json");
                HttpClient client = new HttpClient
                {
                    BaseAddress = new Uri(urlBase)
                };

                string url = $"{servicePrefix}{controller}";
                HttpResponseMessage response = await client.PostAsync(url, content);
                string answer = await response.Content.ReadAsStringAsync();
                Response obj = JsonConvert.DeserializeObject<Response>(answer);
                return obj;
            }
            catch (Exception ex)
            {
                return new Response
                {
                    IsSuccess = false,
                    Message = ex.Message
                };
            }
        }

The problem is that although the response returns a status 200

response

I can’t deserialize the response and cast it to a Response object (always returns false)

anwser

The API response is the following Json: (answer)

{
"firstName":"From",
"lastName":"Manecusei",
"address":"Planeta rojo",
"imageId":"00000000-0000-0000-0000-000000000000",
"imageName":null,
"imageFullPath":"https://martina.blob.core.windows.net/users/noimage.png",
"userType":"Cuidado",
"userTypeId":"35011633-db43-4d99-b0d2-1469471a7054",
"userStatusId":1,
"userStatus":"Registrado",
"fullName":"From Manecusei",
"usersQualifications":0,
"qualification":0,
"id":"0ca72f53-7932-4cb9-af37-13878b35f66a",
"userName":"[email protected]",
"normalizedUserName":"[email protected]",
"email":"[email protected]",
"normalizedEmail":"[email protected]",
"emailConfirmed":false,
"passwordHash":"AQAAAAEAACcQAAAAENxrPVzuqyuyAQOI52GGQK4K1R3KrMd/7ZJQlqkWPBaq1PG3X/ueOtFc0LpnkwXyvA==",
"securityStamp":"Y6EJJUXEN5UTXSUSBOMGBFPDC36VSNFM",
"concurrencyStamp":"44ce0b88-b8f0-4861-804f-52acc29097d6",
"phoneNumber":"88888888",
"phoneNumberConfirmed":false,
"twoFactorEnabled":false,
"lockoutEnd":null,
"lockoutEnabled":true,
"accessFailedCount":0
}

My Response.cs class is as follows:

public class Response
{
    public bool IsSuccess { get; set; }

    public string Message { get; set; }

    public object Result { get; set; }
}

My User.cs class is as follows:

 public class User : IdentityUser
    {
        [Display(Name = "Nombres")]
        [MaxLength(50, ErrorMessage = "El campo {0} no puede tener más de {1} carácteres.")]
        [Required(ErrorMessage = "El campo {0} es obligatorio.")]
        public string FirstName { get; set; }

        [Display(Name = "Apellidos")]
        [MaxLength(50, ErrorMessage = "El campo {0} no puede tener más de {1} carácteres.")]
        [Required(ErrorMessage = "El campo {0} es obligatorio.")]
        public string LastName { get; set; }

        [Display(Name = "Dirección")]
        [MaxLength(100, ErrorMessage = "El campo {0} no puede tener más de {1} carácteres.")]
        public string Address { get; set; }

        [Display(Name = "Foto")]
        public Guid ImageId { get; set; }

        [Display(Name = "Nombre foto")]
        public string ImageName { get; set; }

        // TODO: Fix the images path
        [Display(Name = "Foto")]
        public string ImageFullPath => ImageId == Guid.Empty
          ? $"https://martina.blob.core.windows.net/users/noimage.png"
           : $"https://martina.blob.core.windows.net/users/{ImageId}";
        
        [Display(Name = "Tipo de usuario")]
        public string UserType { get; set; }

        [Display(Name = "Id tipo usuario")]
        public string UserTypeId { get; set; }

        [Display(Name = "Id estado de usuario")]
        public int UserStatusId { get; set; }

        [Display(Name = "Estado de usuario")]
        public string UserStatus { get; set; }

        [Display(Name = "Usuario")]
        public string FullName => $"{FirstName} {LastName}";

        [JsonIgnore]
        public ICollection<UserDisease> UsersDiseases { get; set; }

        [JsonIgnore]
        public ICollection<History> HistoryUsersStatus { get; set; }

        [JsonIgnore]
        public ICollection<Qualification> Qualifications { get; set; }

        [DisplayName("Calificación usuario")]
        public int UsersQualifications => Qualifications == null ? 0 : Qualifications.Count;

        [DisplayFormat(DataFormatString = "{0:N2}")]
        public float Qualification => Qualifications == null || Qualifications.Count == 0 ? 0 : Qualifications.Average(q => q.Score);

    }

What am I doing wrong? Why can’t I deserialize the anwser to an object of type Response?
Any help for me?

Solution

try to use this response class

Response response = JsonConvert.DeserializeObject<Response>(answer);

class

public class Response
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string address { get; set; }
        public string imageId { get; set; }
        public object imageName { get; set; }
        public string imageFullPath { get; set; }
        public string userType { get; set; }
        public string userTypeId { get; set; }
        public int userStatusId { get; set; }
        public string userStatus { get; set; }
        public string fullName { get; set; }
        public int usersQualifications { get; set; }
        public int qualification { get; set; }
        public string id { get; set; }
        public string userName { get; set; }
        public string normalizedUserName { get; set; }
        public string email { get; set; }
        public string normalizedEmail { get; set; }
        public bool emailConfirmed { get; set; }
        public string passwordHash { get; set; }
        public string securityStamp { get; set; }
        public string concurrencyStamp { get; set; }
        public string phoneNumber { get; set; }
        public bool phoneNumberConfirmed { get; set; }
        public bool twoFactorEnabled { get; set; }
        public object lockoutEnd { get; set; }
        public bool lockoutEnabled { get; set; }
        public int accessFailedCount { get; set; }
    }

Answered By – Serge

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *