2016-11-10 344 views
1

我試圖反序列化一個包含Dictionary<string,bool>作爲條目之一的C#Dictionary<string,object>。代碼生成/序列化文件很好,但是當它加載它時,我得到以下錯誤。NewtonSoft.Json,無法反序列化字典中的子字典

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Boolean] 

一直試圖弄清楚現在幾個小時,經過大量的谷歌搜索,我似乎無法弄清楚。源文件有點大,所以我會在下面鏈接它們,而不是發佈完整的文件。

的代碼示數在這個類中獲取函數的返回調用, https://gitlab.com/XerShade/Esmiylara.Online/blob/alpha-2-dev/source/Esmiylara.Frameworks/ConfigurationFile.cs

這裏是我用來測試的ConfigurationFile類參考調試配置類。 https://gitlab.com/XerShade/Esmiylara.Online/blob/alpha-2-dev/source.debug/Esmiylara.Debug/DebugConfig.cs

任何幫助將不勝感激。

編輯:這是生成的JSON文件,以防萬一需要看到它。

{ 
    "RandomStringValue": "Some profound text will appear here!", 
    "RandomBooleans": { 
    "Player 1": false, 
    "Player 2": false, 
    "Player 3": false, 
    "Player 4": false 
    } 
} 
+0

你可以張貼JSON數據 – Ramakrishnan

+0

JSON文件中的數據是存在的,還是你想我跑的代碼,並搶完整的錯誤信息? – XerShade

回答

2

JSON.NET,默認情況下將無法確定從JSON字符串對象類型,所以它會反序列化object類型作爲JToken

但是,您可以使用TypeNameHandling設置更改默認行爲。

例如:

var dict = new Dictionary<string, object>() 
{ 
    { "RandomBooleans", new Dictionary<string, bool>() { {"Player 1", true}, {"Player 2", false} } } 
}; 
var settings = new JsonSerializerSettings() 
{ 
    TypeNameHandling = TypeNameHandling.All 
}; 
var json = JsonConvert.SerializeObject(dict, settings); 
var dictDeserialized = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, settings); 

請注意,您必須通過設置序列化和反序列化調用。

產生看起來是這樣的JSON:

{ 
    "$type":"System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib", 
    "RandomBooleans":{ 
     "$type":"System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Boolean, mscorlib]], mscorlib", 
     "Player 1":true, 
     "Player 2":false 
    } 
} 
+1

這樣做,謝謝。 – XerShade