我目前正在尝试使用Json.NET将JSON字符串反序列化为vb.NET中的对象;之前我已经做了一些设置适当的类,然后使用父类将字符串反序列化为一个对象,并且它们工作得很好但是这个似乎没有完全正确分解.
我试图分解的字符串示例如下:
[ { "value": 12345, "text": "Example Unique Text" }, { "InnerList": [ { "value": 4746, "text": "A duplicated entry of text" }, { "value": 4747, "text": "A duplicated entry of text" }, { "value": 4748, "text": "A duplicated entry of text" }, { "value": 4749, "text": "A duplicated entry of text" }, { "value": 4750, "text": "A duplicated entry of text" }, { "value": 4751, "text": "A duplicated entry of text" }, { "value": 4752, "text": "A duplicated entry of text" }, { "value": 4753, "text": "A duplicated entry of text" }, { "value": 4754, "text": "A duplicated entry of text" }, { "value": 4755, "text": "A duplicated entry of text" } ], "duplicated": "Yes" }, { "value": 15298, "text": "Another Example Unique Text" }, { "value": 959, "text": "Yet more uniqueness" }, { "value": 801, "text": "A final little bit of unique text" } ]
我已经尝试通过一些外部工具传递它们,它们都返回相同的类定义,但它们似乎没有用.所以基于我对JSON的理解,我把以下内容放在一起:
Public Class ItemDetails Public Value As Integer Public Text As String End Class Public Class ItemArray Public DetailList As List(Of ItemDetails) Public Duplicated As String End Class Public Class GeneralArray Public GeneralList As List(Of ItemArray) End Class
GeneralArray是父类,用于解析JSON.
然后我尝试将字符串反序列化为父类.在以下示例中,上面概述的JSON字符串和JSONStringCollection是定义GeneralArray的模块:
Dim JSONString As String JSONString = "<JSONStringDetails>" Dim JSONObj = JsonConvert.DeserializeObject(Of JSONStringCollection.GeneralArray)(JSONString)
遗憾的是,当通过它时,返回以下内容并且例程中断:
An unhandled exception of type
‘Newtonsoft.Json.JsonSerializationException’ occurred in
Newtonsoft.Json.dllAdditional information: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type ‘ShadOS.JSONStringCollection+GeneralArray’ because the
type requires a JSON object (e.g. {“name”:”value”}) to deserialize
correctly.
我错过了什么?
您的JSON字符串表示一个对象数组(您可以看到这一点,因为所有内容都包含在[和]之间).错误消息是“您试图将对象数组反序列化为单个对象”.您的目标类型GeneralArray的行为与数组不同(例如,它不从数组/集合类型继承,也不实现集合接口).
另一个问题是,JSON数组是“混合的” – 它包含一些看起来像ItemDetails的对象和看起来像ItemArray的其他对象.在像VB.NET这样的静态语言中,更难以反序列化为单个不同类型的集合.
一种可能的解决方案是将目标类ItemDetails和ItemArray组合成一个单独的类
Public Class CombinedItem 'properties from ItemDetails Public Value As Integer Public Text As String 'properties from ItemArray Public InnerList As List(Of CombinedItem) Public Duplicated As String End Class
鉴于此类,您的反序列化可能如下所示:
Dim JSONObj = JsonConvert.DeserializeObject(Of List(Of CombinedItem))(JSONString)
这里的关键是你告诉Newtonsoft目标类型是List(Of CombinedItem) – 像目标一样的数组/集合.
现在JSONObj是CombinedItem的集合 – 一些将具有Value / Text属性,其他将具有InnerList / Duplicated属性.