I'm processing responses from an API. API always returns results in the following JSON format:
{
"Message": null,
"Sucess: true,
"Exception": null
"Result": null
}
So i have created the model BaseResponse for it.
public class BaseResponse
{
[JsonProperty("Success")]
public static bool Success { get; set; }
[JsonProperty("Message")]
public dynamic Message { get; set; }
[JsonProperty("Exception")]
public dynamic Exception { get; set; }
}
Depending on the request i'm sending, the result field can contain data in various formats. Let's say Animal and Car.
e.g. Animal
{
"Message": null,
"Sucess: true,
"Exception": null
"Result": {"animal_type": "dog", "animal_name": "bobby"}
}
e.g. Car
{
"Message": null,
"Sucess: true,
"Exception": null
"Result": {"car_type": "4x4", "car_name": "jeep"}
}
So i have also created the models for these various formats.
Animal Model
public class Animal
{
[JsonProperty("animal_type")]
public string AnimalType{ get; set; }
[JsonProperty("animal_name")]
public string AnimalName{ get; set; }
}
Car Model
public class Car
{
[JsonProperty("car_type")]
public string CarType{ get; set; }
[JsonProperty("car_name")]
public string CarName{ get; set; }
}
I also extended the BaseResponse so i can cast to the models. e.g.:
public class CarResponse : BaseResponse
{
[JsonProperty("Result")]
public Car Car{ get; set; }
public static CarResponse FromJson(string json) => JsonConvert.DeserializeObject<CarResponse>(json, Converter.Settings);
}
I am sending a HTTP request, reading the response string and casting to corresponding model using JsonConvert. e.g:
string responseBody = await result.Content.ReadAsStringAsync();
CarResponse carResponse = CarResponse.FromJson(responseBody);
I am wondering what is the best practice to cast from the BaseResponse's result field to a model. Is extending BaseResponse and casting the JSON to corresponding response extension the right approach? Or do i cast to BaseResponse and map from the Result field to a model?