如何反序列化为IREADONLY词典C#

最大F

我正在尝试反序列化json

{
  "Type": "Correction",
  "StartTime": "2007-12-19T03:00:00.0000000-08:00",
  "EndTime": "2007-12-23T23:00:00.0000000-08:00",
  "Parameters": [
    {
      "Key": "Something",
      "Value": "1.8"
    },
    {
      "Key": "Something2",
      "Value": "0.10000000000000001"
    },
    {
      "Key": "Something3",
      "Value": "answer3"
    },
  ],
}

包含在Dto中,包括public IReadOnlyDictionary<string, string> Parameters { get; set; }许多其他内容。

我正在使用最新的newtonsoft反序列化器,该函数具有

var responseObject = JsonConvert.DeserializeObject<TResponse>(jsonResponse);

但它返回错误

Newtonsoft.Json.JsonSerializationException : Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.IReadOnlyDictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

有什么我可以用来帮助将Json响应更改为其他响应的工具,例如

"Parameters": 
    {
      "Something": "1.8",
      "Something2": "0.10000000000000001",
      "Something3": "answer3",
    },

可行(因为删除了数组)。

PS:我使用了正则表达式替换,但是由于最小的json更改可能导致失败,因此我放弃了这种方法。

谢谢!

KFL

好的,这花了我一段时间,但我发现了。

因此,简短的答案是,如果可能的话,使用针对.NET v4.5 +的NewtonSoft.Json版本。但是,如果您的应用程序打算在.NET 4.5及更低版本上运行,则不能使用此功能。

出现该错误的原因是因为您的NewtonSoft.Json定位于v4.5以下的.NET框架。这是因为IReadonlyDictionary.NET v4.5中引入了。是2013年的博客文章,在NewtonSoft 5.0中介绍了.NET v4.5的这一新功能。

newtonsoft.jsonnuget程序包中,有针对不同.NET版本的程序集的多个版本。我曾经ildasm偷看程序集元数据。

对于packages\Newtonsoft.Json.<version>\lib\net40\Newtonsoft.Json.dll,它的TargetFramework设置为v4.0,并且其实现支持反序列化为IReadonlyDictionary

.custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string) = ( 01 00 1A 2E 4E 45 54 46 72 61 6D 65 77 6F 72 6B // ....NETFramework 2C 56 65 72 73 69 6F 6E 3D 76 34 2E 30 01 00 54 // ,Version=v4.0..T 0E 14 46 72 61 6D 65 77 6F 72 6B 44 69 73 70 6C // ..FrameworkDispl 61 79 4E 61 6D 65 10 2E 4E 45 54 20 46 72 61 6D // ayName..NET Fram 65 77 6F 72 6B 20 34 ) // ework 4

对于packages\Newtonsoft.Json.<version>\lib\net45\Newtonsoft.Json.dll,它的TargetFramework设置为v4.5,其实现确实支持反序列化为IReadonlyDictionary

.custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string) = ( 01 00 1A 2E 4E 45 54 46 72 61 6D 65 77 6F 72 6B // ....NETFramework 2C 56 65 72 73 69 6F 6E 3D 76 34 2E 35 01 00 54 // ,Version=v4.5..T 0E 14 46 72 61 6D 65 77 6F 72 6B 44 69 73 70 6C // ..FrameworkDispl 61 79 4E 61 6D 65 12 2E 4E 45 54 20 46 72 61 6D // ayName..NET Fram 65 77 6F 72 6B 20 34 2E 35 ) // ework 4.5

我什至检查了针对.NET 4.5的非常旧的Newtonsoft.Json(v6.0)版本,它确实支持只读字典。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章