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

如何在JSON Schema中解析布尔值true?NJsonSchema解析报错排查

JSON Schema布尔值解析与NJsonSchema报错问题解决

问题1:如何在JSON Schema中解析布尔值true?

在JSON Schema中,定义布尔类型的约束直接使用"type": "boolean"即可。如果需要限定值必须为true,可以添加"const": true关键字来明确约束,示例如下:

{
  "title": "JSONSchemaBoolean",
  "description": "Always valid if true. Never valid if false. Is constant.",
  "type": "boolean",
  "const": true
}

问题2:代码中"default": true是否有效?如何正确解析?

你代码里的"default": true写法无效,这正是NJsonSchema抛出错误的核心原因。

在JSON Schema的properties字段下,每个属性必须是一个Schema对象,而非直接写具体值。你这里的"default"是JSONSchemaObject的一个属性,需要定义它的Schema规则(包括类型、默认值等)。原代码直接写true,不符合Schema的结构要求,所以解析器报错“应为JSON对象或数组”。

修正后的代码

将错误的"default": true替换为标准Schema对象结构,修正后的完整代码如下:

var problemJsonSchema = """
{
    "title": "JSONSchema",
    "default": {},
    "oneOf": [{
            "$ref": "#/definitions/JSONSchemaObject"
        },
        {
            "$ref": "#/definitions/JSONSchemaBoolean"
        }
    ],
    "definitions": {
        "JSONSchemaBoolean": {
            "title": "JSONSchemaBoolean",
            "description": "Always valid if true. Never valid if false. Is constant.",
            "type": "boolean",
            "const": true
        },
        "JSONSchemaObject": {
            "title": "JSONSchemaObject",
            "type": "object",
            "properties": {
                "$id": {
                    "type": "string"
                },
                "default": {
                    "type": "boolean",
                    "default": true
                }
            }
        }
    }
}
""";

var metaSchema = JsonSchema.FromJsonAsync(problemJsonSchema).Result;

修正说明

  1. 调整default属性的定义:把"default": true改为{"type": "boolean", "default": true},其中type定义该属性的类型为布尔值,default指定该属性的默认值为true,完全符合JSON Schema的结构规范。
  2. 完善JSONSchemaBoolean的约束:添加"const": true,明确限定该Schema仅接受布尔值true,匹配你注释中的描述。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:55:19