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

JSON字符串反序列化异常:bfevent始终返回Null求助

问题排查与解决:JSON反序列化BFEvent返回Nothing

核心问题分析

你遇到的问题根源很明确:实体类属性名和JSON中的字段名不匹配。

看你的JSON数据,每个result项里的事件数据是放在"event"字段下的,但你的BFResult类里对应的属性却是bfevent。Newtonsoft.Json默认会按完全一致的名称来映射字段和属性,所以它找不到bfevent对应的JSON字段,自然就返回Nothing了;而marketCount因为属性名和JSON字段名完全一致,所以能正常解析。


两种解决方法

方法一:修改属性名匹配JSON字段

直接把BFResult里的bfevent改成event,但注意event是VB的关键字,需要用方括号包裹来避免语法错误:

Public Class BFResult
    Public Property [event] As BFEvent ' 用方括号包裹关键字
    Public Property marketCount As Integer
End Class

方法二:使用JsonProperty特性映射字段

如果不想修改属性名,可以给bfevent属性加上JsonProperty特性,明确指定它对应的JSON字段名是event:

Imports Newtonsoft.Json ' 需要引入这个命名空间

Public Class BFResult
    <JsonProperty("event")>
    Public Property bfevent As BFEvent
    Public Property marketCount As Integer
End Class

修正后的完整代码示例

这里用方法二的方案给你展示完整代码:

Imports Newtonsoft.Json

strcatalogue = "{ ""jsonrpc"": ""2.0"", ""result"": [{ ""event"": { ""id"": ""29202748"", ""name"": ""Kings XI Punjab v Mumbai Indians"", ""countryCode"": ""GB"", ""timezone"": ""GMT"", ""openDate"": ""2019-03-30T10:30:00.000Z"" }, ""marketCount"": 20 }, { ""event"": { ""id"": ""29201119"", ""name"": ""Victoria v NSW Blues"", ""countryCode"": ""AU"", ""timezone"": ""GMT"", ""openDate"": ""2019-03-27T23:30:00.000Z"" }, ""marketCount"": 2 }, { ""event"": { ""id"": ""29202753"", ""name"": ""Chennai Super Kings v Rajasthan Royals"", ""countryCode"": ""GB"", ""timezone"": ""GMT"", ""openDate"": ""2019-03-31T14:30:00.000Z"" }, ""marketCount"": 35 }], ""id"": 1 }"
Dim objJson = JsonConvert.DeserializeObject(Of BFEventList)(strCatalogue)

Public Class BFEvent
    Public Property id As String
    Public Property name As String
    Public Property countryCode As String
    Public Property timezone As String
    Public Property openDate As DateTime
End Class

Public Class BFResult
    <JsonProperty("event")>
    Public Property bfevent As BFEvent
    Public Property marketCount As Integer
End Class

Public Class BFEventList
    Public Property jsonrpc As String
    Public Property result As BFResult()
    Public Property id As Integer
End Class

现在运行代码,objJson.result里的每个bfevent都会正确解析出JSON中的事件数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:39:33