我正在尝试使用 RestSharp 为 Capsule CRM API 编写包装器。
我对他们的 API 服务有疑问。当 CRM 上存在数据时返回 JSON 对象,当对象不存在时返回空字符串。
例如,查看联系人:
{"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 获取联系人的空字符串时出现异常:
Unable to cast object of type 'System.String' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
如何避免这个问题? 有什么方法可以根据API返回的数据进行条件匹配吗? 我如何告诉 RestSharp 不要抛出异常,如果不匹配就跳过属性?
最佳答案
因为您可以控制您的 API,而不是在响应中返回 "contacts":""
,而是返回 "contacts":"{}"
,这应该避免你的错误。
如果您无法更改来自 API 的响应,则需要实现自定义序列化程序,因为 RestSharp 不支持对象的“”。
This article总结了如何使用 JSON.Net作为序列化程序,这将使您能够使用反序列化所需的任何规则。
文章摘要
首先,执行ISerializer和 IDeserializer NewtonsoftJsonSerializer
类中的接口(interface)。这将使您完全控制 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;
}
关于c# - 如何使用 RestSharp 实现反序列化规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35313661/