VB.Net项目JSON.Net反序列化复杂对象报错无法将JSON数组转为指定类型
问题排查与解决方案
问题原因
- 核心报错触发原因:JSON结构中
tokenScopeList是数组类型,现有类定义中对集合类型的声明存在歧义,且集合未提前初始化,序列化库无法自动填充元素。 - 缺失类定义:现有代码未声明
Identity、Namespace(对应JSON中identity下的namespace字段)两个类,反序列化时无法匹配对应嵌套结构。 - 可空类型不匹配:JSON中部分int类型字段(如第二个tokenScopeList项的org.id、user.id)会返回null,直接声明为不可空
Integer会导致类型不兼容报错。 - 关键字冲突:JSON中的
namespace是VB保留关键字,直接作为类名/属性名会触发语法错误,需要转义。
修复方案
以下为修正后的完整类定义,兼容你提供的JSON结构:
Public Class RootobjectLogin Public Property data As DataumLogin Public Property meta As Meta End Class Public Class DataumLogin Public Property expiresAt As Date Public Property createdAt As Date Public Property identityId As Integer Public Property identity As Identity ' 替换为List(Of T)适配JSON数组,提前初始化避免空引用 Public Property tokenScopeList As New List(Of Tokenscopelist) Public Property token As String End Class ' 补全缺失的Identity类 Public Class Identity Public Property id As Integer ' 方括号转义VB关键字namespace Public Property [namespace] As [Namespace] End Class ' 补全缺失的Namespace类,方括号转义关键字 Public Class [Namespace] Public Property id As Integer Public Property nickname As String End Class Public Class Tokenscopelist Public Property org As Org Public Property user As User Public Property scope As New List(Of String) End Class Public Class Packageplan Public Property id As Integer Public Property package As Package Public Property isSelected As Boolean End Class Public Class Package Public Property id As Integer Public Property name As String Public Property packageFeatures As New List(Of Packagefeature) End Class Public Class Packagefeature Public Property config As Config Public Property id As Integer Public Property feature As Feature End Class Public Class Config ' 可空类型适配null值 Public Property count As Integer? End Class Public Class Feature Public Property id As Integer Public Property name As String Public Property code As String End Class Public Class User ' 可空整型适配null返回值 Public Property id As Integer? Public Property opal As String End Class Public Class Org ' 可空整型适配null返回值 Public Property id As Integer? Public Property name As String Public Property opal As String Public Property parentOrg As Object Public Property packagePlans As New List(Of Packageplan) End Class Public Class Meta ' 接口返回null直接用Object接收即可 Public Property accessToken As Object End Class
额外注意事项
- 若使用Newtonsoft.Json反序列化,可添加配置忽略空值不匹配问题:
Dim result = JsonConvert.DeserializeObject(Of RootobjectLogin)(json字符串, New JsonSerializerSettings With {.NullValueHandling = NullValueHandling.Ignore}) - 若使用System.Text.Json反序列化,对应配置为:
Dim result = JsonSerializer.Deserialize(Of RootobjectLogin)(json字符串, New JsonSerializerOptions With {.IgnoreNullValues = True}) - 若日期格式反序列化失败,可在Date类型属性上添加对应的序列化特性指定日期格式即可。
内容的提问来源于stack exchange,提问作者Bernie 406
相关产品推荐
相关产品推荐

