【发布时间】:2021-02-16 16:55:35
【问题描述】:
我看到了“类似问题”,但尝试了所有这些并没有解决我的问题。 我有一个这样的Json
{
"externalId": "pobj124",
"dossierNumber": "Test 20210216",
"issuedDate": "2021-01-28T23:00:00+00:00",
"issuedPlace": "New-York",
"properties": {
"documentTypeId": 7,
"countryLayout": "US"
}
}
属性是未知数量的“名称”:“值”。不知道名称和价值。 我的班级被定义为
<Serializable>
Public Class Document
Public Property externalId As String
Public Property dossierNumber As String
Public Property issuedDate As Date
Public Property issuedPlace As String
Public Property properties As IDictionary(Of String, String)
End Class
调用代码是
Private Function DeserializeJson(json As String) As Document
Return JsonConvert.DeserializeObject(Of Document)(json)
End Function
反序列化字典似乎不是正确的方法。 错误是
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'Document',因为该类型需要 JSON 对象(例如 {"name":"value"}) 正确反序列化。要修复此错误 将 JSON 更改为 JSON 对象(例如 {"name":"value"})或更改 将类型反序列化为数组或实现集合的类型 接口(例如 ICollection、IList),例如 List 可以 从 JSON 数组反序列化。也可以添加 JsonArrayAttribute 强制它从 JSON 数组反序列化。
到目前为止我已经尝试过:
Public Property properties As IDictionary(Of String, String)
Public Property properties As List(Of KeyValuePair(Of String, String))
Public Property properties As Dictionary(Of String, String)
Public Property properties() As KeyValuePair(Of String, String)
【问题讨论】:
-
这个错误与 Dictionary 无关,而是 JSON Object 本身,它似乎是 Array 的一部分。发布完整的 JSON。
-
无法复制,请参阅dotnetfiddle.net/avWPPM。您问题中的 JSON 可以反序列化为您问题中的
Document类型。请edit 分享您的问题minimal reproducible example。正如 Jimi 所提到的,可能实际导致问题的 JSON 在某处包含一个数组。 -
好吧,你说得对,我有一些数组。我已将它们更改为 List(Of 并且它现在正在反序列化我的 Dictionary。该错误使我感到困惑,因为它在一个只有 Dictionary 属性的类中,但该类本身在一个数组中使用。谢谢你的帮助。跨度>
标签: vb.net serialization json.net