Is there any standard way of handling JSON responses that contain a common field which could be returned as Array (JArray) or Object (JObject)?
Sample: Both responses come from the same endpoint. If request failed response 1 (field data => of type array)
{
"code": "1",
"message": "Chatterjee",
"data": [{"test"}],
}
If request was successfull response 2 (field data => of type object)
{
"code": "1",
"message": "Chatterjee",
"data": {
"name": "test"
},
}
Right now I have two types which I use for deserialization.
public abstract class PushHubBaseResult
{
public PushHubErrorCode Code { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public abstract object GetData();
}
public class PushHubResult : PushHubBaseResult
{
public JArray Data { get; set; }
public override object GetData()
{
return Data;
}
}
public class PushHubResultTransfer : PushHubBaseResult
{
public JObject Data { get; set; }
public override object GetData()
{
return Data;
}
}
Depending on the request success I will have one or two deserializations.
IRestResponse<PushHubResultTransfer> result = client.Deserialize<PushHubResultTransfer>(response);
if (result.IsSuccessful)
return result.Data;
else
{
// Try to deserialize failed response
IRestResponse<PushHubResult> resultFailed = client.Deserialize<PushHubResult>(response);
if (resultFailed.Data != null)
return resultFailed.Data;
}
How can I handle it by just having one deserilization? Like:
IRestResponse<TypeX> result = client.Deserialize<TypeX>(response);
if (result.IsSuccessful)
return result.Data;
else
{
if (resultFailed.Data != null)
return resultFailed.Data;
}
Update:
I switched to "dynamic" to make it work with a single class. Because there is no casting done on the backend. It is forwarded to the JS Client 1:1 in this case.
public class PushHubResult
{
public PushHubErrorCode Code { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public dynamic Data { get; set; }
}