自定义多态性Newtonsoft JSON DESERIALIZER



i具有递归数据结构。类似...

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中对此进行审理。

您可以看到,确定是否使用ComplexComparison还是SimpleComparison的唯一方法是确定.Left值是字符串还是对象。(nb他们既可以是字符串又是对象)

所以,我正在写一个自定义转换器,并且已经走了很远...

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")obj("Right")JToken类型)上重新启动避难所?或者我应该将它们施加到JObject,然后将此代码分为单独的功能,然后递归地将其称为?

事实证明它比我预期的要简单,而json.net为我做了所有繁重的举重...

Public Overrides Function ReadJson(reader As Newtonsoft.Json.JsonReader, objectType As Type, existingValue As Object, serializer As Newtonsoft.Json.JsonSerializer) As Object
    Dim Ret As Comparison
    Dim JComparison As JObject = JObject.Load(reader)
    If JComparison("Left").GetType.IsAssignableFrom(GetType(JValue)) Then
        Ret = New SimpleComparison
    Else
        Ret = New ComplexComparison
    End If
    serializer.Populate(JComparison.CreateReader(), Ret)
    Return Ret
End Function

相关内容

  • 没有找到相关文章

最新更新