Search code examples
c#restapicastingapi-design

How do I convert an object passed from an api back to that item's class?


In my api I have a class with a few fields including one of type object. I insert an object of another class into that field. Then I return the entire class back to the program calling the api. In that program, I can convert the entire result to the class it was originally, but I can't convert the object field back to it's original class. What am I missing?

API

public class APIResponse
{
    public int statusCode { get; set; }
    public string errorMessage { get; set; }
    public object returnObject { get; set; }
}

[HttpPost("CompleteCustomFilterOrder")]
[Produces("application/json", Type = typeof(APIResponse))]
public APIResponse GetItem
{
    ItemDTO item = new ItemDTO();
    item.ID = 12345
    item.Name = "Widget";
    item.Status = "Active";

    APIResponse response = new APIResponse();
    response.statusCode = 98765;
    response.errorMessage = "Success!";
    response.returnObject = item;

    return response;
}

Program calling API

        var client = new RestClient(url + "GetItem");
        var request = new RestRequest(Method.GET);
        var apiResponse = client.Execute<APIResponse>(request);
        APIResponse response = apiResponse.Data;

        ItemDTO item = (ItemDTO)response.returnObject;

Response correctly gets converted back to a class, but item throws the error

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'ProjectName.BusinessLogicLayer.Classes.ItemDTO'.

The ItemDTO class is identical in both programs except for the namespace.


Solution

  • You are reciving JSON object as a response so direct cast won't work. You need to deserialize this object using eg. JsonConvert from Newtonsoft.Json. Btw. did you consider making APIResponse a generic class ?

    public class APIResponse<T> where T: class
    {
        public int statusCode { get; set; }
        public string errorMessage { get; set; }
        public T returnObject { get; set; }
    }