我有一个递归数据结构。就像是...
Public Class Comparison
Property Id As Integer
End Class
Public Class SimpleComparison
Inherits Comparison
Property Left As String
Property Right As String
End Class
Public Class ComplexComparison
Inherits Comparison
Property Left As Comparison
Property Right As Comparison
End Class
我需要从 JSON 反序列化到这个。
如您所见,确定是使用 aComplexComparison
还是 a的唯一方法SimpleComparison
是确定该.Left
值是字符串还是对象。(注意它们要么都是字符串,要么都是对象)
所以,我正在编写一个自定义转换器并且已经到了这一步......
Public Class ComparisonConverter
Inherits Newtonsoft.Json.JsonConverter
''<Snip>
Public Overrides Function ReadJson(reader As Newtonsoft.Json.JsonReader, objectType As Type, existingValue As Object, serializer As Newtonsoft.Json.JsonSerializer) As Object
Dim obj As JObject = TryCast(serializer.Deserialize(Of JToken)(reader), JObject)
If obj IsNot Nothing Then
''We''ve got something to work with
Dim Id As Integer = obj("Id").ToObject(Of Integer)()
''Check if we''re instantiating a simple or a complex comparison
If obj("Left").GetType.IsAssignableFrom(GetType(JValue)) Then
''LHS is a string - Simple...
Return New SimpleComparison With {
.Id = Id,
.Left = obj("Left").ToObject(Of String)(),
.Right = obj("Right").ToObject(Of String)()}
Else
Return New ComplexComparison With {
.Id = Id,
.Left = ???, '' <<Problem
.Right = ???}'' <<Problem
End If
Else
Return Nothing
End If
End Function
End Class
由于对象复杂而导致的分支If
是我卡住的地方。如何在obj("Left")
and obj("Right")
(类型为JToken
)上重新调用反序列化器?或者我应该将它们转换为JObject
然后将此代码分解为一个单独的函数并递归调用它?