I developed an API method that is called from other C# method.
I defined this class:
public class ApiResult
{
public bool success { get; set; }
public string message { get; set; } = string.Empty;
public object? data { get; set; }
}
Note the data
property.
Then I do this:
public static async Task<ApiResult?> GetAsync(string baseUrl, string endpoint)
{
using var client = new RestClient(baseUrl);
var request = new RestRequest(endpoint, Method.Get);
var response = await client.ExecuteAsync<ApiResult>(request);
return response.Data; // ApiResult instance is returned
}
When I construct the ApiResult
object, I populate data
property with an instance of a class called Persona
.
Finally I can see that response.Data
contains this object:
response.data
{Modules.Integration.ApiModels.ApiResult}
data: ValueKind = Object : "{"tipoDocumentoId":3,"centroCostoId":0,"centroCostoNombre":"","departamentoId":0,"departamentoNombre":"","cargoId":0,"cargoNombre":"","codigo":11727935,"nombres":"Jaime","apellidos":"Stuardo","email":null,"fechaNacimiento":null,"sexo":"M","telefono":null,"tarjeta":null,"patente":null,"codigoInterno":null,"fechaContrato":null,"nombreFoto":null,"ssn":"117279359","ssnFormateado":"11.727.935-9","id":2,"estaVigente":true,"fechaCreacion":"2023-05-24T09:20:57.2","fechaActualizacion":null}"
message: ""
success: true
See the ApiResult.data
property, which contains the Persona
instance but not as an intance of the Persona
object but a JSON object.
How can I make RestSharp to deserialize the JSON object into the actual object instance?
EDIT:
Here is what I expect following by what I am receiving:
expectedResult
{Modules.Integration.ApiModels.ApiResult}
data: {Modules.Integration.ApiModels.Persona}
message: ""
success: true
actualResult
{Modules.Integration.ApiModels.ApiResult}
data: ValueKind = Object : "{"tipoDocumentoId":3,"centroCostoId":0,"centroCostoNombre":"","departamentoId":0,"departamentoNombre":"","cargoId":0,"cargoNombre":"","codigo":11727935,"nombres":"Jaime","apellidos":"Stuardo","email":null,"fechaNacimiento":null,"sexo":"M","telefono":null,"tarjeta":null,"patente":null,"codigoInterno":null,"fechaContrato":null,"nombreFoto":null,"ssn":"117279359","ssnFormateado":"11.727.935-9","id":2,"estaVigente":true,"fechaCreacion":"2023-05-24T09:20:57.2","fechaActualizacion":null}"
message: ""
success: true
Finally I have deserialized that object by myself.
I created this extension method:
public static T? ToObject<T>(this object? o)
{
if (o is null || !(o is JsonElement))
return default;
return ((JsonElement)o).Deserialize<T>();
}
And then, I called it this way:
var persona = RestConnection.Get<ApiResult>(baseUrl, string.Format(endpoint, ssn))?.data.ToObject<Persona>();
RestConnection
is a class that encapsulates RestSharp
calls.