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

Windows PowerShell中Newtonsoft.Json验证JSON Schema报错如何解决?

在PowerShell中验证JSON与JSON Schema一致性的问题解决

一、PowerShell 7原生解决方案:Test-Json命令

在PowerShell 7中,直接使用内置的Test-Json命令即可完成JSON与Schema的一致性验证,示例代码如下:

$Json = @'
{
  "name": "James",
  "hobbies": [".NET", "Blogging", "Reading", "Xbox", "LOLCATS"]
}
'@

$JsonSchema = @'
{
  "description": "A person",
  "type": "object",
  "required": ["name", "hobbies"],
  "properties":
  {
    "name": {"type":"string"},
    "hobbies": {
      "type": "array",
      "items": {"type":"string"}
    }
  }
}
'@

Test-Json -Json $Json -Schema $JsonSchema
# 输出:True

二、直接使用Newtonsoft.Json遇到的错误

尝试直接调用PowerShell 7默认提供的Newtonsoft.Json类时,执行以下代码会报错:

$Schema = [Newtonsoft.Json.Schema.JsonSchema]::Parse($JsonSchema)
$JObject = [Newtonsoft.Json.Linq.JObject]::Parse($Json)
$JObject.IsValid($Schema)

错误信息:

OperationStopped: C:\Users\Gebruiker\GDrive\Scripts\PowerShell\_JIO\Yaml\Test-Yaml.ps1:31
Line |
  31 |  $JObject.IsValid($Schema)
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~
     | Target type System.Collections.IEnumerator is not a value type or a non-abstract class. (Parameter 'targetType')

三、修复方案与替代方案

方案1:明确指定IsValid方法的重载

错误源于PowerShell解析IsValid方法时匹配了不合适的重载版本,通过强制指定参数类型可调用正确重载:

# 明确调用接受JsonSchema参数的重载
$isValidMethod = [Newtonsoft.Json.Linq.JObject].GetMethod('IsValid', [type[]]@([Newtonsoft.Json.Schema.JsonSchema]))
$isValidMethod.Invoke($JObject, @($Schema))

方案2:使用JsonSchemaValidation类验证(含错误详情)

借助Newtonsoft.Json.Schema.JsonSchemaValidation类的静态方法,既能完成验证,还能获取详细错误信息:

$reader = [Newtonsoft.Json.JsonTextReader]::New([System.IO.StringReader]::New($Json))
$validator = [Newtonsoft.Json.Schema.JsonSchemaValidator]::New($Schema)

try {
    while ($reader.Read()) {
        $validator.Validate($reader)
    }
    $true # 验证通过返回True
}
catch [Newtonsoft.Json.Schema.JsonSchemaValidationException] {
    $_.Exception.Message # 输出具体验证错误
}
finally {
    $reader.Dispose()
}

方案3:优先使用原生Test-Json命令

如果环境是PowerShell 7及以上版本,强烈推荐直接使用Test-Json命令——它已封装Newtonsoft.Json的验证逻辑,用法简洁,无需处理.NET方法调用的兼容性问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:43:36