【发布时间】:2015-10-03 11:59:44
【问题描述】:
我正在尝试反序列化 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"
},
],
}
包含public IReadOnlyDictionary<string, string> Parameters { get; set; } 以及许多其他内容的 DTO。
我正在使用最新的 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",
},
哪个有效(因为数组已被删除)。
附:我使用了正则表达式替换,但由于最小的 JSON 更改可能导致它失败,所以我放弃了这种方法。
【问题讨论】:
-
我可以不用自定义反序列化器吗? ;) 对这些不太熟悉。
-
请附上您正在使用的一些代码。您收到的错误消息表明您正在尝试将“[...]”形式的某些内容反序列化为对象。
-
您是否考虑过使用
dynamic类型而不是TResponse? -
您的 JSON 包含一个序列化为键/值对数组的字典。
DataContractJsonSerializer默认执行此操作。您可以从这里使用DictionaryToArrayConverter:stackoverflow.com/questions/27332723/…
标签: c# json json-deserialization