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

Newtonsoft生成2020-12版JSON Schema时prefixItems使用错误致无效

问题分析与解决

问题重现

在基于Sparx EA的C#插件中,使用Newtonsoft.Json.Schema生成JSON Schema 2020-12版本时,数组类型属性生成了不符合规范的prefixItems字段——该字段值为单个对象,而非JSON Schema要求的数组;切换到2019-09版本时则正常生成items字段。尝试设置propertySchema.ItemsPositionValidation = false也无法解决问题。

原因判断

这大概率是Newtonsoft.Json.Schema在处理2020-12版本Schema时的版本兼容bug:

  • JSON Schema 2020-12规范中,prefixItems用于定义数组前N个元素的逐个规则,必须是数组类型;而items变为所有未被prefixItems覆盖的数组元素的默认规则。
  • 旧版本的Newtonsoft.Json.Schema在将单个Items schema转换为2020-12格式时,错误地直接将对象赋值给prefixItems,而非包装成单元素数组。
  • ItemsPositionValidation参数的设计可能未适配2020-12版本的逻辑,导致设置后不生效。

解决方法

  1. 升级Newtonsoft.Json.Schema到最新稳定版
    优先尝试升级库版本,官方可能已修复该兼容性问题。在NuGet包管理器中更新Newtonsoft.Json.Schema至最新版后重新测试。

  2. 手动修正生成的Schema
    若升级后问题仍存在,可在生成Schema后手动处理数组类型的节点:

    // 假设生成的schema为JsonSchema类型的rootSchema
    foreach (var property in rootSchema.Properties.Values)
    {
        if (property.Type.HasFlag(JsonSchemaType.Array) && property.PrefixItems != null && !property.PrefixItems.IsArray)
        {
            // 将单个对象包装成数组
            var singleItem = property.PrefixItems;
            property.PrefixItems = new JsonSchemaArray { singleItem };
            // 可选:设置items为该默认规则,保持与2019-09版本的行为一致
            property.Items = singleItem;
        }
    }
    
  3. 手动构建数组Schema
    不依赖自动生成,直接为数组类型属性构建符合2020-12规范的Schema:

    var arrayPropertySchema = new JsonSchema
    {
        Type = JsonSchemaType.Array,
        PrefixItems = new JsonSchemaArray { itemSchema }, // itemSchema为数组元素的Schema
        Items = itemSchema // 设置默认元素规则
    };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:19:58