gpt4 book ai didi

json - 如何将 JSON Schema 链接到我的 JSON 以验证 JSON?

转载 作者:行者123 更新时间:2023-12-02 03:08:07 33 4
gpt4 key购买 nike

我是 JSON Schema 的新手,读过什么是 JSON Schema 等等。但我不知道如何将 JSON Schema 链接到 JSON 以针对该 JSON Schema 进行验证。谁能解释一下?
请任何人都可以用简单的话向我解释我如何将 JSON 模式链接到 JSON 文件以根据 JSON 模式检查和验证 JSON 文件数据?

最佳答案

查看 json.net 标记,我得出结论,您打算在 C# 中针对 json 数据进行 JSON 数据验证。

这非常简单/直接。

  • 您将架构解析为 JsonSchema 对象实例。
  • 将 json 数据解析为 JObject 对象实例。
  • 调用IsValid 实例变量的JObject 方法(以解析后的JsonSchema 对象实例为参数)。此方法调用将返回 bool - true 如果有效,false 如果无效。

  • 这里有2个完整的例子

    模式是有效的例子
    string schemaJson = @"{
    'description': 'A person',
    'type': 'object',
    'properties':
    {
    'name': {'type':'string'},
    'hobbies': {
    'type': 'array',
    'items': {'type':'string'}
    }
    }
    }";

    JsonSchema schema = JsonSchema.Parse(schemaJson);

    JObject person = JObject.Parse(@"{
    'name': 'James',
    'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
    }");

    bool valid = person.IsValid(schema);
    // true

    架构是一致的示例
    JsonSchema schema = JsonSchema.Parse(schemaJson);

    JObject person = JObject.Parse(@"{
    'name': null,
    'hobbies': ['Invalid content', 0.123456789]
    }");

    IList<string> messages;
    bool valid = person.IsValid(schema, out messages);
    // false
    // Invalid type. Expected String but got Null. Line 2, position 21.
    // Invalid type. Expected String but got Float. Line 3, position 51.

    来源: newtonsoft.com / Validating JSON with JSON Schema

    更新 1: 看起来架构验证已移出到它自己的库/Nuget 包中。但是请注意,在商业项目中使用这个并不是完全免费的(如果这是您的情况)。定价页面有更多信息。

    Json.NET Schema - Complete JSON Schema framework for .NET

    这里还有一个在线 json 模式验证器 => http://www.jsonschemavalidator.net/

    关于json - 如何将 JSON Schema 链接到我的 JSON 以验证 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41411329/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com