使用 Response 反序列化 Json
deserialize a Json using a Response
我正在尝试反序列化我的 Xamarin 应用程序中 API 提供的响应,如下所示:
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
};
}
}
问题是虽然响应returns状态为200
我无法反序列化响应并将其转换为 Response 对象(始终 returns false)
API 响应如下 Json:(答案)
{
"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":"froummahegafreu-4693@yopmail.com",
"normalizedUserName":"FROUMMAHEGAFREU-4693@YOPMAIL.COM",
"email":"froummahegafreu-4693@yopmail.com",
"normalizedEmail":"FROUMMAHEGAFREU-4693@YOPMAIL.COM",
"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
}
我的Response.csclass如下:
public class Response
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
public object Result { get; set; }
}
我的User.csclass如下:
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);
}
我做错了什么?为什么我不能将 anwser 反序列化为 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; }
}
我正在尝试反序列化我的 Xamarin 应用程序中 API 提供的响应,如下所示:
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
};
}
}
问题是虽然响应returns状态为200
我无法反序列化响应并将其转换为 Response 对象(始终 returns false)
API 响应如下 Json:(答案)
{
"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":"froummahegafreu-4693@yopmail.com",
"normalizedUserName":"FROUMMAHEGAFREU-4693@YOPMAIL.COM",
"email":"froummahegafreu-4693@yopmail.com",
"normalizedEmail":"FROUMMAHEGAFREU-4693@YOPMAIL.COM",
"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
}
我的Response.csclass如下:
public class Response
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
public object Result { get; set; }
}
我的User.csclass如下:
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);
}
我做错了什么?为什么我不能将 anwser 反序列化为 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; }
}