Anloboz
Anloboz

Reputation: 183

Newtonsoft.Json - Deserialize generic object into a wrapper class

I'am trying to develop Asp.Net Web Api which response will be always

public class ApiResponse : IApiResponse, IHttpActionResult
{
    private readonly HttpRequestMessage _request;
    private readonly HttpStatusCode _statusCode;
    private readonly string _message;

    [IgnoreDataMember]
    protected Type ResponseDataType { get; set; }

    [DataMember(Name = "data")]
    public object Data { get; private set; }

    [DataMember(Name = "dataType")]
    public string DataType => this.ResponseDataType.Name;

    [DataMember(Name = "additionalMessage")]
    public string AdditionalMessage => this._message;


    public ApiResponse(HttpRequestMessage request, HttpStatusCode responseStatus, Type dataType, object data = null, string additionalMessage = null)
    {
        this._request = request;
        this._statusCode = responseStatus;

        this.ResponseDataType = dataType;
        this.Data = data;
        this._message = additionalMessage;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = _request.CreateResponse(_statusCode, this);
        return Task.FromResult(response);
    }
}

How can i deserialize this kind of response to obtain a cast of the Data property into a object of type DataType?

For example if the response is serialized into this Json

"dataType": "UserModel"
"data":
{
   "name" : "Bill",
   "surname" : "Lob"
}

How can i deserialize this response with Newtonsoft.Json to cast "object data" into "UserModel data"? There is some way?

Upvotes: 3

Views: 741

Answers (1)

Anloboz
Anloboz

Reputation: 183

I have figured out the solution of this situation, it is very simple. In the WebApiConfig.cs file of the api project, i have added this line of code

config.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() { TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All };

this will add an additional Json field called $type used by the deserializer to correctly cast the generic object Data to an UserModel Data

Upvotes: 1

Related Questions