2016-02-10 40 views
0

我正在嘗試使用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不要拋出異常,只是跳過屬性,如果它不匹配?

+0

我沒有看到字典是你的班? – NikolaiDante

+0

我猜RestSharp在內部使用IDictionary來進行屬性值匹配:Contacts是IDictionary,其中包含鍵「Address」,「Phone」,「Website」。 – Anton

+1

作爲臨時解決方案我從響應中刪除「contacts」:「」。 – Anton

回答

3

由於您可以控制API而不是在響應中返回"contacts":"",因此請返回"contacts":"{}"並且應避免出現錯誤。


如果你不能改變來自API的響應,你需要實現自定義序列,如「」反對不RestSharp支持。

This article總結了如何使用JSON.Net作爲序列化程序,這將使您能夠使用任何您需要的規則來進行反序列化。

文章摘要

一是落實在NewtonsoftJsonSerializerISerializerIDeserializer接口。這可以讓你完全控制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; 
} 
+0

它不是我的API,它是Capsule CRM的公共API,我無法更改響應。 :-( – Anton

+0

好吧,我只是假設你是因爲你在評論中的臨時解決方案 – NikolaiDante