I'm using Json.NET to deserialize the response from a third party restful API (don't have control over this and unfortunately can't use a different one). The API returns either a response object or an error object.
At the moment both my response and error objects inherit from a base object and I deserialize to that and then cast to the type that it is.
var response = JsonConvert.DeserializeObject<BaseMessage>(responseContent);
switch (response)
{
case ResponseMessage responseMessage:
return responseMessage;
case ErrorMessage error:
return error;
}
The ResponseMessage
and ErrorMessage
are nothing alike, nor contain a field that says which type it is. I just know from the schema. Imagine they're like the following.
public class BaseMessage
{
}
public class ResponseMessage : BaseMessage
{
public string Status { get; set; }
public string Reference { get; set; }
}
public class ErrorMessage : BaseMessage
{
public string ErrorCode { get; set; }
public string ErrorMessage { get; set; }
}
The only reason that they both inherit from BaseMessage is so that I can deserialize to that type and then cast to the type that it actually should be.
Is there a better way of knowing which object the JSON should deserialize to?