JSON序列化/反序列化为包含字典的字典

时间:2012-06-07 15:10:41

标签: c# serialization json.net deserialization

我正在开发一个实现DotSpatial选项卡/功能区应用程序的项目。每个标签都是一个插件。保存项目时,RaiseSaveRequest事件处理程序会创建一个字典,通过e传递给每个插件的projectSavedListener。然后在监听器中,e.dictPackedStates.adds(pluginName,PackState())进入每个插件的PackState(),将自己打包成字典。因此,整个应用程序的状态保存在dictPackedStates字典中,从pluginName,每个插件的字典开始。

我正在使用JSON.NET在文件保存/打开时序列化/反序列化。我认为我的保存工作正常。

Dictionary<string, object> pluginStates = new Dictionary<string, object>();
signaller.RaiseSaveRequest(pluginStates);

//JSON
string json = JsonConvert.SerializeObject(pluginStates);
StreamWriter sw = new StreamWriter(strPathName); 
sw.Write(json);
sw.Close();

我的sw.Write(json);似乎是将JSON写入文件。我可以打开文件并查看所有内容。然后在我公开场合,我有:

Dictionary<string, object> pluginStates = new Dictionary<string, object>();

//JSON
StreamReader sr = new StreamReader(fullName);
string json = sr.ReadToEnd();
pluginStates = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
sr.Close();

signaller.UnpackProjectState(pluginStates);

我的插件状态与序列化之前的方式不同。当他们得到保存时,字典看起来像:(希望在这里看到它的样子,无法弄清楚如何)..

pluginStates  Count=5, 
(hit plus, 1st entry) [0] {[Project Manager, System.Collections.Generic.Dictionary'2[System.String,System.Object]]}
(hit plus on that entry) Key  "Project Manager" Value  Count =1
(hit plus on value) [0]  {[ProjectName, test5.vbpx]}

然后在open中,它接收到的信号器.UnpackProjectState发送的PluginStates是:

pluginStates  Count=5 
(hit plus, 1st entry)  [0] {[Project Manager, { "ProjectName": "test5.vbpx"}]}
(hit plus)  Key  "Project Manager"  Value  { "ProjectName": "test5.vbpx"}
(hit plus on value) .. first thing is base {Newtonsoft.Json.Linq.Jcontainer}

这会导致第一个插件的UnpackState(对象objPackedState)出错。发送的对象是值{“ProjectName”:“test5.vbpx”},而不是{[Project Manager,System.Collections.Generic.Dictionary'2 [System.String,System.Object])上保存的字典中的第1项。 ]}。

我希望这足以解释我的问题。有关如何获取deserializeObject以正确格式返回字典的任何建议? 非常感谢!!

1 个答案:

答案 0 :(得分:1)

我解决了这个问题(然后找到了我的下一个问题......我将作为一个单独的问题添加)。我更改了pluginStates字典,该字典包含从Dictionary<string, object>Dictionary<string, Dictionary<string, object>>的所有插件的打包状态,这些状态使得保存的pluginStates(在序列化之前)和打开的pluginStates(在反序列化之后)相同。直到我深入了解实际插件的解包方法,该方法未被正确反序列化。

相关问题