RestSharp无法反序列化int body值

时间:2016-10-13 12:29:47

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

我有一个返回整数值的服务,如下例所示:

WebAPI Integer Result

现在,我正在尝试使用Restsharp来使用此服务,如下所示:

    public static Task<T> ExecuteRequestAsync<T>(RestClient restClient, RestRequest request) where T : new()
    {
        var taskCompletionSource = new TaskCompletionSource<T>();
        restClient.ExecuteAsync<T>(request, response =>
        {
            if (response.IsSuccessful())
                taskCompletionSource.SetResult(response.Data);
            else
                taskCompletionSource.SetException(HandleResponseError(response));
        });

        return taskCompletionSource.Task;
    }

    private async Task<int> example() {

        //Get a new RestClient
        var restClient = new RestsharpManager.Builder()
            .WithAuthenticator(new RequestsAuthenticator())
            .Build();

        //Parameters
        var request = new RestRequest
        {
            Method = Method.GET,
            Resource = "integration/install/size"
        };

        //Add parameters
        request.AddParameter("productID", productID);
        request.AddParameter("integrationID", integrationID);
        request.AddParameter("currentVersion", currentVersion);

        //Execute
        return await ExecuteRequestAsync<int>(restClient, request);         

    }       

结果,我们收到以下错误: Error after executing this request

我们缺少什么?另一种响应类型,如Poco类,正确反序列化。看看第二个图像中显示的'content'属性包含应该显示的正确值。

我知道我可以手动解析它,但我想知道为什么restClient.ExecuteAsync<T>没有返回所需的值。

1 个答案:

答案 0 :(得分:0)

我找到了造成这个问题的原因......

Json Deserializer&#39; Restsharp附带的功能无法自动反序列化。

实施&#39;自定义解串器&#39;基于Newtonsoft.Json库解决了这个问题。

Bellow是Custom Serializer / Deserializer及其使用方法:

public class NewtonsoftJsonSerializer : ISerializer, IDeserializer
{
    private readonly JsonSerializer _serializer;

    public NewtonsoftJsonSerializer(JsonSerializer serializer)
    {
        _serializer = serializer;
    }

    public static NewtonsoftJsonSerializer Default => new NewtonsoftJsonSerializer(new JsonSerializer
    {
        NullValueHandling = NullValueHandling.Ignore
    });

    public T Deserialize<T>(IRestResponse response)
    {
        var content = response.Content;

        using (var stringReader = new StringReader(content))
        {
            using (var jsonTextReader = new JsonTextReader(stringReader))
            {
                return _serializer.Deserialize<T>(jsonTextReader);
            }
        }
    }

    public string DateFormat { get; set; }

    public string Namespace { get; set; }

    public string RootElement { get; set; }

    string ISerializer.ContentType
    {
        get { return "application/json"; }

        set { }
    }

    public string Serialize(object obj)
    {
        using (var stringWriter = new StringWriter())
        {
            using (var jsonTextWriter = new JsonTextWriter(stringWriter))
            {
                _serializer.Serialize(jsonTextWriter, obj);

                return stringWriter.ToString();
            }
        }
    }
}

使用它来序列化&#39;您的对象,请按以下方式配置Request

    var request = new RestRequest
    {
        Method = Method.GET,
        RequestFormat = DataFormat.Json,
        JsonSerializer = NewtonsoftJsonSerializer.Default, //<= HERE!!!
        Resource = "integration/install/size"
    };

并且,将其注册为&#39;默认&#39; JSON反序列化器:

    //Creates the RestClient...
    var restClient = new RestClient
    {
        BaseUrl = new Uri(_baseUrl),
        Authenticator = _authenticator
    };

    //Defines the jsonSerializer that will handle the responses
    var jsonSerializer = NewtonsoftJsonSerializer.Default;
    restClient.AddHandler("application/json", jsonSerializer);
    restClient.AddHandler("text/json", jsonSerializer);
    restClient.AddHandler("text/x-json", jsonSerializer);
    restClient.AddHandler("text/javascript", jsonSerializer);
    restClient.AddHandler("*+json", jsonSerializer);