【问题标题】:NewtonSoft.Json, Unable to deserialize a child dictionary in a dictionaryNewtonSoft.Json,无法反序列化字典中的子字典
【发布时间】:2016-11-10 04:57:33
【问题描述】:

我正在尝试反序列化包含 Dictionary<string,bool> 作为条目之一的 C# Dictionary<string,object>。该代码可以很好地生成/序列化文件,但是当它加载它时出现以下错误。

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

几个小时以来一直试图弄清楚这一点,经过多次谷歌搜索后,我似乎无法弄清楚。源文件有点大,所以我将它们链接在下面而不是发布完整文件。

代码在此类的 Get 函数中返回调用时出错, 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
  }
}

【问题讨论】:

  • 你能把json数据发一下吗
  • JSON 文件数据在那里,或者你想让我运行代码并获取完整的错误详细信息?

标签: c# json dictionary serialization


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多