【问题标题】:How to implement deserialization rules with RestSharp?如何用 RestSharp 实现反序列化规则?
【发布时间】:2016-02-10 20:53:14
【问题描述】:

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

他们的 API 服务有问题。它在数据存在时返回 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"}}

为了匹配我上课的联系人:

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

我要匹配的类中的属性联系人:

public Contacts Contacts { get; set; }

当 API 返回 JSON 对象时一切正常,但当我从 API 获取联系人的空字符串时出现异常:

无法将“System.String”类型的对象转换为类型 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'。

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

【问题讨论】:

  • 我没有看到您的课程中的字典在哪里?
  • 我猜 RestSharp 在内部使用 IDictionary 进行属性值匹配:联系人是 IDictionary,键为“地址”、“电话”、“网站”。
  • 作为临时解决方案,我从响应中删除了 "contacts":""。

标签: c# json restsharp


【解决方案1】:

由于您可以控制自己的 API,因此不要在响应中返回 "contacts":"",而是返回 "contacts":"{}",这样可以避免您的错误。


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

This article 总结了如何使用JSON.Net 作为序列化程序,这将使您能够使用反序列化所需的任何规则。

文章摘要

首先,在NewtonsoftJsonSerializer 类中实现ISerializerIDeserializer 接口。这将使您可以完全控制 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;
}

【讨论】:

  • 这不是我的API,是Capsule CRM的公共API,我无法更改响应。 :-(
  • 啊好吧,我只是假设因为你在 cmets 中的临时解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多