【问题标题】:How Do I Validate a JSON file With a Schema in VB.Net?如何在 VB.Net 中使用模式验证 JSON 文件?
【发布时间】:2021-06-11 21:35:06
【问题描述】:

我正在尝试验证 VB.net 上的一些 JSON 文件。 但是,每当我运行我的代码时,它就会卡住

Dim Schema As JsonSchema = JsonSchema.Parse(SchemaString)

错误提示

Newtonsoft.Json.dll 中出现“Newtonsoft.Json.JsonException”类型的未处理异常。

还有一个警告说 JSON 验证移到了它自己的包中。所以,我很确定我只是导入了错误的包,但我不确定。

如果有人能指出我正确的方向,我将不胜感激,

谢谢。

这是我的 VB.net 代码

Imports System
Imports Newtonsoft.Json.Schema
Imports Newtonsoft.Json.Linq

Public Function Validate_JSON()

    Dim SplunkPath As String = "Z:\Database Project\Splunk Folder\Dropbox\Splunk_File.json"
    Dim SchemaPath As String = "Z:\Database Project\Schema Folder\Schema_File.json"
    Dim Schema_String As String = My.Computer.FileSystem.ReadAllText(SchemaPath)
    Dim Schema As JsonSchema = JsonSchema.Parse(Schema_String)
    Dim Data_String As String = My.Computer.FileSystem.ReadAllText(SplunkPath)
    Dim Data_JSON As JObject = JObject.Parse(Data_String)

    Dim Splunk_Status As Boolean = Data_JSON.IsValid(Schema)

    Return 0

End Function

这里是 Splunk_File.json

{
  "Site": "USI",
  "SN": "21165",
  "MN": "F2C00W",
  "DateTime": "05/18/2021"
}

这里是 Schema_File.json

{
    "$schema" :"http://json-schema.org/draft-04/schema",
  "properties": {
    "$schema": "#",
    "Site": {
      "type": "string"
    },
    "SN": {
      "Type": "string"
    },
    "MN": {
      "Type": "string"
    }
}
}

【问题讨论】:

  • 我们需要一个minimal reproducible example 来帮助您,特别是SchemaString 的内容和一个可以证明问题的具体JSON_String
  • 感谢您的反馈。我已经对我的问题进行了更改。随时询问有关我的代码的更多问题。
  • 尝试从“MN”块中删除尾随逗号。
  • 我进行了更正,但在解析()我的架构字符串时发生了同样的错误。
  • 警告是因为 JamesNK 将模式实现移到了自己的库中。主 JSON 库中的内容是用于向后兼容的旧代码,但它仍应支持草案 4(如您使用的那样)。

标签: json vb.net json.net jsonschema


【解决方案1】:

$schema 仅在根中有效,properties 值必须是架构。

properties 内部有一个 "$schema" : "#"。这意味着您试图说您的 JSON 对象应该具有一个名为 schema 的属性,该属性可以针对 schema # 进行验证。但# 不是有效的模式对象,因此解析失败。

您需要从您的properties 中删除$schema


我还建议使用更高版本的架构规范草案(如果您可以控制架构)。 Draft 6 是与最新版本 2020-12 兼容的最旧版本。

但为此,您可能需要使用不同的验证包。有几种可用。我的是JsonSchema.Net

【讨论】:

    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 2023-02-01
    • 2013-10-23
    • 2017-07-03
    • 1970-01-01
    • 2018-08-18
    • 2012-11-28
    • 2020-03-21
    相关资源
    最近更新 更多