在Visual Basic .NET中反序列化JSON

在Visual Basic .NET中反序列化JSON,第1张

在Visual Basic .NET中反序列化JSON

您可以做的是创建一个

JsonConverter
,以正确的顺序将您的
Actor
类序列化为
IEnumerable<object>
,然后在反序列化中使用LINQ
to
JSON

读取JSON,检查所读取的令牌是否为数组,然后以等效顺序设置属性

您可以为您的

Actor
类对此进行硬编码,但是我认为创建一个通用转换器会更有趣,该通用转换器使用POCO类型的属性顺序将不可枚举的POCO往返于JSON数组。可以使用
<JsonProperty(Order:=NNN)>
属性在您的班级中指定此顺序。

因此,转换器:

Public Class ObjectToArrayConverter(Of T)    Inherits JsonConverter    Public Overrides Function CanConvert(objectType As Type) As Boolean        Return GetType(T) = objectType    End Function    Private Shared Function ShouldSkip(p As JsonProperty) As Boolean        Return p.Ignored Or Not p.Readable Or Not p.Writable    End Function    Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)        If value Is Nothing Then writer.WriteNull()        Else Dim type = value.GetType() Dim contract = TryCast(serializer.ContractResolver.ResolveContract(type), JsonObjectContract) If contract Is Nothing Then     Throw New JsonSerializationException("invalid type " & type.FullName) End If Dim list = contract.Properties.Where(Function(p) Not ShouldSkip(p)).Select(Function(p) p.ValueProvider.GetValue(value)) serializer.Serialize(writer, list)        End If    End Sub    Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object        If reader.TokenType = JTokenType.Null Then Return Nothing        End If        Dim token = JArray.Load(reader)        Dim contract = TryCast(serializer.ContractResolver.ResolveContract(objectType), JsonObjectContract)        If contract Is Nothing Then Throw New JsonSerializationException("invalid type " & objectType.FullName)        End If        Dim value = If(existingValue, contract.DefaultCreator()())        For Each pair In contract.Properties.Where(Function(p) Not ShouldSkip(p)).Zip(token, Function(p, v) New With { Key.Value = v, Key.Property = p }) Dim propertyValue = pair.Value.ToObject(pair.Property.PropertyType, serializer) pair.Property.ValueProvider.SetValue(value, propertyValue)        Next        Return value    End FunctionEnd Class

和你的班级:

<JsonConverter(GetType(ObjectToArrayConverter(Of Actor)))> _Public Class Actor    ' Use [JsonProperty(Order=x)] //http://www.newtonsoft.com/json/help/html/JsonPropertyOrder.htm to explicitly set the order of properties    <JsonProperty(Order := 0)> _    Public Property Name As String    <JsonProperty(Order := 1)> _    Public Property NumberOfMovies As Integer    <JsonProperty(Order := 2)> _    Public Property NumberOfAwards As Integer    <JsonProperty(Order := 3)> _    Public Property NumberOfTVshows As IntegerEnd Class

工作提琴。

请注意,

JsonConverter
可以在此处找到处理适用于属性的属性的更新的c#版本。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5622965.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存