我正在嘗試使用RestSharp爲Capsule CRM API編寫包裝。如何使用RestSharp實現反序列化規則?
我的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不要拋出異常,只是跳過屬性,如果它不匹配?
我沒有看到字典是你的班? – NikolaiDante
我猜RestSharp在內部使用IDictionary來進行屬性值匹配:Contacts是IDictionary,其中包含鍵「Address」,「Phone」,「Website」。 – Anton
作爲臨時解決方案我從響應中刪除「contacts」:「」。 – Anton