Newtonsoft.Json-将通用对象反序列化为包装类

时间:2018-07-10 17:55:06

标签: c# asp.net-web-api json.net

我正在尝试开发始终保持响应状态的Asp.Net Web Api

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);
    }
}

我如何反序列化这种响应,以将Data属性转换为类型DataType的对象?

例如,如果响应已序列化到此Json

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

我如何使用Newtonsoft.Json反序列化此响应以将“ object data”转换为“ UserModel data”? 有办法吗?

1 个答案:

答案 0 :(得分:1)

我已经弄清楚了这种情况的解决方案,这很简单。 在api项目的WebApiConfig.cs文件中,我添加了这一行代码

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

这将添加一个称为$type的附加Json字段,由反序列化器使用,以将通用object Data正确地转换为UserModel Data