【问题标题】:JSON serialize/deserialize to dictionary containing dictionariesJSON 序列化/反序列化为包含字典的字典
【发布时间】:2012-06-07 15:10:40
【问题描述】:

我正在开发一个实现 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 与它们被序列化之前的方式不同。当他们被保存时,字典看起来像:(想在这里有一张它的样子,不知道如何)..

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]}

然后在公开的情况下,signaller.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(object objPackedState) 出错。发送的对象是值 { "ProjectName": "test5.vbpx"} 而不是上面保存的字典中的第一项 {[Project Manager, System.Collections.Generic.Dictionary'2[System.String,System.Object] ]}。

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

【问题讨论】:

  • 我认为我正走在解决问题的正确道路上。具有 key:pluginName & value:packedDictionary 的主字典被设置为字典。我将其更改为字典。现在,我收到一条错误消息:无法将类型为“Newtonsoft.Json.Linq.JArray”的对象转换为在第一个插件中输入“System.Data.DataTable”,我试图像这样重新填充其状态: this.dt = (DataTable)dictPluginState["DT"];我有字典进入 UnpackState.. Unpack(dictionary dictPluginState。有什么建议吗??

标签: c# serialization json.net deserialization


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多