Web API - Converting JSON to Complex Object Type (DTO) with inheritance

爷,独闯天下 提交于 2019-12-11 21:26:21

问题


I have the following scenario:

public class WidgetBaseDTO
{
    public int WidgetID
    {
        get;
        set;
    }
}

public class WidgetTypeA : WidgetBaseDTO
{
    public string SomeProperty1
    {
        get;
        set;
    }
}


public class WidgetTypeB : WidgetBaseDTO
{
    public int SomeProperty2
    {
        get;
        set;
    }
}

and my web service returns the following dashboard object whereas the Widgets collection could be of either type A or B:

public class DashboardDTO
{
    public List<WidgetBaseDTO> Widgets
    {
        get;
        set;
    }
}

my problem is that although the client receives correct JSON content, which is dependent on the Widget type, when reading the response content, they are all being translated to WidgetBaseDTO. what is the correct way to convert these objects to the relevant types?

this is how the response is being read:

string relativeRequestUri = string.Format("api/dashboards/GetDashboard?dashboardID={0}", dashboardID);
using (var client = new HttpClient())
{
    // set client options
    client.BaseAddress = this.BaseUri;
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // make request               
    HttpResponseMessage response = client.GetAsync(relativeRequestUri).Result;
    if (response.IsSuccessStatusCode)
    {                   
        DashboardDTO dashboard = response.Content.ReadAsAsync<DashboardDTO>().Result;
    }

回答1:


I believe after receiving the response you are probably trying to cast WidgetBaseDTO to either WidgetTypeA or WidgetTypeB and you are seeing null? if yes, then you can try after making the following setting to the Json formatter on the server...make sure to make this setting on the client side's json formatter too.

config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects;

The above setting will cause the type information of WidgetTypeA or WidgetTypeB to be put over the wire which gives a hint to the client as to the actual type of the object being deserialized...you can try looking at the wire format of the response to get an idea...

Client side:

JsonMediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
jsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects;
WidgetBaseDTO baseDTO = resp.Content.ReadAsAsync<WidgetBaseDTO>(new MediaTypeFormatter[] { jsonFormatter }).Result;


来源:https://stackoverflow.com/questions/22725751/web-api-converting-json-to-complex-object-type-dto-with-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!