运行后将DeserializeObject从通用类型转换为已知类型

时间:2019-06-13 03:19:30

标签: c# .net generics json.net

我正在调用第三方API,该API根据布尔“成功”字段返回通用结果。结果是基于结果响应的已知类型类。

我正在以非常愚蠢的方式将类反序列化object,并读取结果。

读取结果后,我将对象再次序列化为JSON,然后将对象反序列化回到对应的正确结果/已知数据类型。

我想问的问题是,什么是实现这一目标的有效或更好的方法

来自第三方API的示例响应

如果成功是false

    {
        "Success": false,
        "Result": 
        {
            "ErrorCode": "1",
            "ErrorMessage": "Request is unsuccessful."
        }
    }

如果成功为true

    {
        "Success": true,
        "Result": 
        {
            "UserID": "xxxxx",
            "UserName": "yyyyy",
            "UserAge": 60
        }
    }

我的代码

我的呼叫方法(如何改进此呼叫方法?

var request = new RequestModel ("user1", "password1");
var data = await CallThirdPartyAPI(request);
//At this point of time, this `data` is a `Message<object>` data type
if (data.Success)
{
    var passResult = JsonConvert.SerializeObject(data); //Serialize object type back to JSON 
    var passObject = JsonConvert.DeserializeObject<Message<SuccessResponse>>(passResult); //Deserialize object back to known data type
}
else
{
    var failResult = JsonConvert.SerializeObject(data); //Serialize object type back to JSON
    var failObject = JsonConvert.DeserializeObject<Message<FailResponse>>(failResult); //Deserialize object back to known data type
}

API方法

public async Task<Message<object>> CallThirdPartyAPI(RequestModel requestModel)
{
    var requestUrl = CreateRequestUri(string.Format(System.Globalization.CultureInfo.InvariantCulture,
        "api/thirdpartyapi/"));
    var result =  await PostAsync<object, requestModel>(requestUrl, requestModel);
    return result;
}


// Common method for making POST calls
private async Task<Message<T1>> PostAsync<T1, T2>(Uri requestUrl, T2 content)
{                 
    var response = await _httpClient.PostAsync(requestUrl.ToString(), CreateHttpContent<T2>(content));
    response.EnsureSuccessStatusCode();
    var data = await response.Content.ReadAsStringAsync();
    var result =  JsonConvert.DeserializeObject<Message<T1>>(data);
    return result;
}

DTO

public class Message<T>
{
    [DataMember(Name = "Success")]
    public bool Success { get; set; }

    [DataMember(Name = "Result")]
    public T Result { get; set; }
}

public class FailResponse
{
    public string ErrorCode { get; set; }
    public string ErrorMessage { get; set; }
}

public class SuccessResponse
{
    public string UserId{ get; set; }
    public string UserName { get; set; }
    public int UserAge{ get; set; }
}

public class RequestModel
{
 public string UserName { get; set; }
 public string Password { get; set; }
}

0 个答案:

没有答案