2014-01-24 168 views
0

調用API時,我得到如下回應(這是預期的,它是處理不好的查詢功能測試的一部分):問題反序列化JSON響應

HTTP/1.1 400 Bad Request Date: Fri, 24 Jan 2014 17:43:39 GMT Sforce-Limit-Info: api-usage=5/5000 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked

16F [{"message":"\nSELECT id, name, description FROM BadObject\n
^\nERROR at Row:1:Column:35\nsObject type 'BadObject' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names.","errorCode":"INVALID_TYPE"}] 0

我試圖把它反序列化到下面的類:

public class ErrorResponse 
{ 
    public string message; 
    public string errorCode; 
} 

使用下面的代碼:

var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(response); 

然而,當我嘗試反序列化,我得到以下錯誤:

{"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Salesforce.Common.Models.ErrorResponse' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath '', line 1, position 1."}

我懷疑這是\ n(換行符)導致的問題。我嘗試用「\ n」替換「\ n」,但它沒有奏效。

想法?

回答

1

因爲JSON被方括號包圍,所以它是一個數組。您需要反序列化成接受多個條目的對象。例如:

public class ErrorResponses : List<ErrorResponse> { } 

public class ErrorResponse 
{ 
    public string message; 
    public string errorCode; 
} 

然後你就可以反序列化,像這樣:

var errorResponse = JsonConvert.DeserializeObject<ErrorResponses>(json); 
0

如果我明白你做的很好的東西,你只需要把它反序列化到一個列表<錯誤響應>而不是錯誤響應。