You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET反序列化JSON至Test类遇JsonReaderException求助

问题:JSON反序列化为Test类时抛出JsonReaderException异常

异常信息

Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Unexpected character encountered while parsing value: [. Path 'Array1', line 4, position 14.

待反序列化的JSON文本

{
    "Name1": "Value1",
    "Name2": "Value2",  
    "Array1":["a", "b", "c", "d"]
}

对应的Test类定义

Public Class Test
    Public Property Name1 As String
    Public Property Name2 As String
    Public Property Array1() As String
End Class

主模块代码

Imports System
Imports System.IO
Imports System.Collections.Generic
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Serialization
Imports Newtonsoft.Json.Converters
Imports Newtonsoft.Json.Linq
Module Module1

    Sub Main()
        
       '从JSON文件读取内容到strJsonText,执行下方代码时抛出异常
        Dim classDocs = JsonConvert.DeserializeObject(strJsonText, GetType(Test))

    End Sub

End Module

解决方法

问题出在Test类的Array1属性定义上:Public Property Array1() As String是VB.NET的**参数数组(ParamArray)**语法,而非普通的字符串数组定义。Newtonsoft.Json无法将JSON数组反序列化为参数数组类型,因此解析到[字符时触发异常。

修改方案1:改为普通字符串数组属性

将Test类中的Array1定义修改为:

Public Class Test
    Public Property Name1 As String
    Public Property Name2 As String
    Public Property Array1 As String()
End Class

修改方案2:改用List(Of String)类型(推荐)

如果需要更灵活的集合操作,也可以将属性类型改为泛型列表:

Public Class Test
    Public Property Name1 As String
    Public Property Name2 As String
    Public Property Array1 As List(Of String)
End Class

修改后重新执行反序列化代码即可正常解析JSON数组。


内容的提问来源于stack exchange,提问作者Chembu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:31:05