Json.NET Schema IsValid returns 即使有不同的类型也是如此

Json.NET Schema IsValid returns true even if there is different type

我有简单的 JSON 对象和 JSON 架构。 JSON 对象 属性 名称是字符串。在模式中,我期待整数。 IsValid 方法 return 为真。我认为它应该 return 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();

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

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

.NET Fiddle

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

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

使用架构生成器 (Netonsoft.Json.Schema) 命名空间/nuget 包生成您的 class 架构

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

schema.ToString();