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

Max*_*axF 6 c# json json-deserialization

我正在尝试反序列化 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"
    },
  ],
}
Run Code Online (Sandbox Code Playgroud)

进入一个 Dto 包括public IReadOnlyDictionary<string, string> Parameters { get; set; } 许多其他的东西。

我正在使用最新的 newtonsoft 解串器,其功能是

var responseObject = JsonConvert.DeserializeObject<TResponse>(jsonResponse);
Run Code Online (Sandbox Code Playgroud)

但它返回错误

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.
Run Code Online (Sandbox Code Playgroud)

是否有任何工具可以帮助我将 Json 响应更改为不同的响应,例如

"Parameters": 
    {
      "Something": "1.8",
      "Something2": "0.10000000000000001",
      "Something3": "answer3",
    },
Run Code Online (Sandbox Code Playgroud)

哪个有效(因为删除了数组)。

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

谢谢!

KFL*_*KFL 6

好的,这花了我一段时间,但我想通了。

所以简短的回答是,如果可能,使用面向 .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) 版本,它确实支持只读字典。