在RestSharp中正常处理空的json对象

Tho*_*mas 10 .net c# restsharp

我有以下代码:

public void GetJson()
{
    RestRequest request = new RestRequest(Method.GET);

    var data = Execute<Dictionary<string, MyObject>>(request);
}

public T Execute<T>(RestRequest request) where T : new()
{
    RestClient client = new RestClient(baseUrl);
    client.AddHandler("text/plain", new JsonDeserializer());

    var response = client.Execute<T>(request);

    return response.Data;
}
Run Code Online (Sandbox Code Playgroud)

问题是有时响应将是一个空的json数组[].当我运行此代码时,我得到以下异常:无法将类型为'RestSharp.JsonArray'的对象强制转换为'System.Collections.Generic.IDictionary`2 [System.String,System.Object]'.

有没有办法优雅地处理这个?

jfr*_*484 0

我从来没有需要过 client.AddHandler 行,所以我不确定你是否需要它。不过,请尝试为您的 Execute 方法执行此操作:

public T Execute<T>(RestRequest request) where T : class, new()
{
    RestClient client = new RestClient(baseUrl);
    client.AddHandler("text/plain", new JsonDeserializer());

    try
    {
        var response = client.Execute<T>(request);
        return response.Data;
    }
    catch (Exception ex)
    {
        // This is ugly, but if you don't want to bury any errors except when trying to deserialize an empty array to a dictionary...
        if (ex is InvalidCastException && typeof(T) == typeof(Dictionary<string, MyObject>))
        {
            // Log the exception?
            return new T();
        }

        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)