【问题标题】:Json.NET Schema IsValid returns true even if there is different type即使有不同的类型,Json.NET Schema IsValid 也会返回 true
【发布时间】:2018-04-21 17:29:35
【问题描述】:

我有简单的 JSON 对象和 JSON 模式。 JSON 对象属性名称为字符串。在模式中我期待整数。 IsValid 方法返回 true。我认为它应该返回 false,因为存在类型不匹配。我错过了什么?

//json
var hero = new Hero();
hero.Name = "Egid Beyond Meta";
hero.BattleRank = 5000;

var output = JsonConvert.SerializeObject(hero);
var deserialized = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(output);

        // schema
        string schema = @"{
          'title' : 'Hero',
          'type' : 'object',
          'Name' : {'type' : 'integer'},
          'BattleRank' : {'type' : 'integer'},
          required: [ 'Name', 'BattleRank']
        }";

        var jsonSchema = JSchema.Parse(schema);

        // returns ture
        Console.WriteLine("is valid " + deserialized.IsValid(jsonSchema));
        Console.ReadLine();

【问题讨论】:

    标签: c# json json.net jsonschema


    【解决方案1】:

    您必须在架构的properties 属性中定义您的对象属性,如下所示:

    string schema = @"{
        'title' : 'Hero',
        'type' : 'object',
        'properties': {
            'Name' : {'type' : 'integer'},
            'BattleRank' : {'type' : 'integer'},
        },
        required: [ 'Name', 'BattleRank']
    }";
    

    .NET Fiddle

    【讨论】:

      【解决方案2】:

      您的架构不正确,应该是:

      {
        "type": "object",
        "properties": {
          "Name"      : { "type": ["string"]},
          "BattleRank": { "type": "integer"}
        },
        "required": ["Name","BattleRank"]
      }
      

      使用模式生成器 (Netonsoft.Json.Schema) 命名空间/nuget 包生成类的模式

      JSchemaGenerator generator = new JSchemaGenerator();
      JSchema schema = generator.Generate(typeof(Hero));
      
      schema.ToString();
      

      【讨论】:

      • 真正的问题:为什么有一个数组用于Name的类型?
      • 它不是一个数组,而是它允许添加其他项目,例如"Name" : { "type" : ["string", null]}。对于我们的测试目的,它可能是"Name" : { "type" : "string"};我不喜欢它。
      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      相关资源
      最近更新 更多