我正在尝试反序列化具有虚拟属性的json对象。请参阅此最小样本来说明我的问题:
Dim jsonInput As String = "{""props"": {""dogOnlyProperty"":42} }"
Dim jss As New JavaScriptSerializer()
Dim stuffObj As Stuff = jss.Deserialize(Of Stuff)(jsonInput)
Public Class Stuff
Public props As Animal.AnimalProperties
End Class
Public MustInherit Class Animal
Public MustInherit Class AnimalProperties
End Class
Public name As String
Public MustOverride Function GetCustomProperties() As AnimalProperties
End Class
Public Class Dog
Inherits Animal
Public Class DogProperties
Inherits AnimalProperties
Public dogOnlyProperty As Integer
End Class
Public Overrides Function GetCustomProperties() As Animal.AnimalProperties
Return New DogProperties()
End Function
End Class
Public Class Cat
Inherits Animal
Public Class CatProperties
Inherits AnimalProperties
Public catOnlyProperty As String
End Class
Public Overrides Function GetCustomProperties() As Animal.AnimalProperties
Return New CatProperties()
End Function
End Class
上面的代码引发异常,因为序列化程序不知道AnimalProperties的真实类型。 如何告诉序列化程序我知道AnimalProperties应该被转换为DogProperties?
(如果有人想要C#版本,我可以写它。)
答案 0 :(得分:0)
在这里找到了anwser: How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?
我用JSON.NET更改了本机序列化程序,并编写了一个自定义的jsonConverter。