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

JSON Schema转VB.Net集合代码失效问题技术咨询

JSON Schema转VB.Net模型及Newtonsoft反序列化问题解答

问题背景

从未使用过Newtonsoft,尝试通过在线工具将含$ref引用的3500行JSON Schema转换为VB.Net(或先转C#再转换)模型对象,多次尝试均失败,问题疑似与集合或Schema文件本身的引用处理有关。

Schema核心片段

根对象定义:

"properties": {
    "Properties": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true,
      "items": {
        "$ref": "#/definitions/Property"
      }
    }
}

Property对象定义:

"Property": {
  "type": "object",
  "required": [
    "Name",
    "Location",
    "ID",
    "ObjectType"
  ],
  "properties": {
    "Messages": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true,
      "items": {
        "$ref": "#/definitions/Message"
      }
    },
    "Name": {
      "$ref": "#/definitions/$basicType/definitions/requiredString"
    },
    "Location": {
      "$ref": "#/definitions/$basicType/definitions/requiredString"
    },
    ... more of same...
}

样本JSON片段:

"Properties":[{"ID":"33...

在线工具转换问题

  • 使用jsonutils.com转换VB.Net时,生成两个同名Properties类,集合未转为Property对象集合,所有items集合均被转为Items类
  • 使用JSON2Csharp转换C#时,items属性无对应类,存在错误

问题解答

1. 处理含$ref的JSON Schema转换工具

可以使用Newtonsoft.Json.Schema库自带的代码生成功能,它能正确解析Schema中的$ref引用,生成对应VB.Net或C#类:

  • 加载完整Schema文件到JsonSchema对象
  • 通过SchemaGenerator配置目标语言后生成代码,能准确识别嵌套引用和集合定义,避免类名重复或映射错误

另外,Visual Studio的“粘贴JSON为类”功能也可用,但需要准备一份覆盖所有Schema字段和引用的完整JSON样本,基于样本生成的模型类同样能正确对应集合和引用关系。

2. Newtonsoft反序列化对List(Of Property)的支持

完全可以使用List(Of Property)这类集合类型对应Schema中的数组定义。只要模型类结构与JSON结构匹配,Newtonsoft.Json能自动将JSON数组反序列化为List(Of Property)、IEnumerable(Of Property)或Property()数组。

VB.Net示例模型结构:

Public Class RootObject
    Public Property Properties As List(Of [Property])
End Class

Public Class [Property]
    <JsonProperty(Required := Required.Always)>
    Public Property Name As String
    <JsonProperty(Required := Required.Always)>
    Public Property Location As String
    <JsonProperty(Required := Required.Always)>
    Public Property ID As String
    <JsonProperty(Required := Required.Always)>
    Public Property ObjectType As String
    Public Property Messages As List(Of Message)
End Class

Public Class Message
    ' 根据Schema定义添加对应属性
End Class

使用JsonConvert.DeserializeObject(Of RootObject)(jsonString)即可完成正常反序列化。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:03:21