如何使用 RestSharp 实现反序列化规则?

How to implement deserialization rules with RestSharp?

我正在尝试使用 RestSharp 为 Capsule CRM API 编写包装程序。

我对他们的 API 服务有疑问。当数据存在时它 returns JSON 对象,当 CRM 上没有对象时它是空字符串。

例如,查看联系人:

{"organisation":{"id":"97377548","contacts":"","pictureURL":"","createdOn":"2016-02-08T14:27:12Z","updatedOn":"2016-02-08T14:27:12Z","lastContactedOn":"2013-12-03T21:00:00Z","name":"some name"}}

{"organisation":{"id":"97377548","contacts":{"email":{"id":"188218414","emailAddress":"someemail"},"phone":{"id":"188218415","type":"Direct","phoneNumber":"phone"}},"pictureURL":"","createdOn":"2016-02-08T14:27:12Z","updatedOn":"2016-02-08T14:27:12Z","lastContactedOn":"2013-12-03T21:00:00Z","name":"some name"}}

匹配我有的联系人 class:

public class Contacts
{
    public List<Address> Address { get; set; }
    public List<Phone> Phone { get; set; }
    public List<Website> Website { get; set; }
    public List<Email> Email { get; set; }
}
我正在尝试匹配

和 属性 class 中的联系人:

public Contacts Contacts { get; set; }

当 API returns JSON 对象时一切正常,但是当我从 API:

获取联系人的空字符串时出现异常

Unable to cast object of type 'System.String' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.

如何避免这个问题? 有没有办法根据API返回的数据进行条件匹配? 我如何告诉 RestSharp 不要抛出异常,如果不匹配就跳过 属性?

由于您可以控制 API,而不是在响应中 returning "contacts":"",return "contacts":"{}" 应该可以避免您的错误.


如果您无法更改 API 的响应,您将需要实施自定义序列化程序,因为 RestSharp 不支持对象的“”。

This article summarizes how to use JSON.Net 作为序列化程序,这将使您能够使用反序列化所需的任何规则。

文章摘要

首先,在NewtonsoftJsonSerializerclass中实现ISerializer and IDeserializer接口。这将使您完全控制 JSON 的反序列化方式,因此您可以使 "" 为空对象工作。

然后,根据请求使用它:

 private void SetJsonContent(RestRequest request, object obj)
 {
     request.RequestFormat = DataFormat.Json;
     request.JsonSerializer = new NewtonsoftJsonSerializer();
     request.AddJsonBody(obj);
 }

并在响应中使用它:

private RestClient CreateClient(string baseUrl)
{
    var client = new RestClient(baseUrl);

    // Override with Newtonsoft JSON Handler
    client.AddHandler("application/json", new NewtonsoftJsonSerializer());
    client.AddHandler("text/json", new NewtonsoftJsonSerializer());
    client.AddHandler("text/x-json", new NewtonsoftJsonSerializer());
    client.AddHandler("text/javascript", new NewtonsoftJsonSerializer());
    client.AddHandler("*+json", new NewtonsoftJsonSerializer());

    return client;
}