2012-06-01 69 views
1

反序列化JSON任意對象我想反序列化一個JSON〜應變這樣與JSON.NET

{ 
    "status":"1", 
    "since":"1245626956', 
    "list":{ 
     "1":{ 
     "item_id":"1" 
     }, 
     "2":{ 
     "item_id":"2" 
     } 
    } 
} 

爲此,我有一個分析該

public class ListResponse 
{ 
    public String status { get; set; } 
    public String since { get; set; } 
    public IDictionary<String, Item> list { get; set; } 
} 

我用這句話的對象:

ListResponse list = JsonConvert.DeserializeObject<ListResponse>(message); 

這很好,但我有一個問題,因爲響應可以是這樣的

{ 
    "status":"1", 
    "since":"1245626956', 
    "list":[] 
} 

當試圖反序列化異常引發,因爲需要一個數組來解析'列表',但我的對象有一個IDictionary。

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.IDictionary`2[System.String,Item]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 
To 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<T> 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. 

我該如何處理這個問題,而不使用Linq來獲取JObject並執行「手動」映射?

+0

爲什麼你'list'獲得不同的價值?它應該一直是一本字典或一個數組,對嗎? –

+0

它必須是一致的,但是當列表不爲空時是一個字典,當爲空時是一個數組。如果我在調試時修改字符串,將''list':[]'改爲'「list」:{}'沒有錯誤。 – emenegro

+1

當你的JSON數據的源代碼是空而不是'[]'時,你的JSON數據源不應該給你嗎?有什麼方法可以解決這個問題嗎? –

回答

2

一個簡單的解決辦法是反序列化之前,要做到這一點:

yourString = yourString.Replace("\"list\":[]", "\"list\":{}"); 
+2

這是我認爲的第一件事,但它是我不喜歡太多的補丁。我無法對源做任何事情,因爲我正在使用公共API提供的服務。 – emenegro