Json.NET针对Schema验证JSON数组 [英] Json.NET validate JSON array against Schema
问题描述
我要验证具有数组的模式,所有这些都需要一次调用validate方法.我是用javascript完成的,但是我想用 Json.NET 在C#中做到这一点.使用Json.NET,我可以像这样对数组中的每个对象调用验证方法:
I want to validate a schema which has an array, all in one call to the validate method. I did it in javascript but I am sturggling to do it in C# with Json.NET. With Json.NET I am calling the validation method for each object in the array like so:
JSchema schema = JSchema.Parse(@"{
'title': 'HouseCollection',
'description': '',
'$schema': 'http://json-schema.org/draft-04/schema#',
'definitions': {
'Categories': {
'title': 'Categories',
'description': '',
'$schema': 'http://json-schema.org/draft-04/schema#',
'type': 'object',
'additionalProperties': false,
'properties': {
'serviceCode': {
'description': 'xxx,
'type': 'string'
}
},
'required': [
'serviceCode'
]
},
'House': {
'title': 'House',
'description': '',
'$schema': 'http://json-schema.org/draft-04/schema#',
'type': 'object',
'additionalProperties': false,
'properties': {
'aaa': {
'type': 'string'
},
'bbb': {
'type': 'string'
},
'ccc': {
'description': 'xxx',
'type': 'string'
},
'ddd': {
'type': 'number'
},
'eee': {
'description': 'xxx',
'type': 'boolean'
},
'fff': {
'description': 'xxx',
'type': 'string'
},
'ggg': {
'description': 'xxx',
'type': 'string'
},
'hhh': {
'type': 'number'
},
'iii': {
'description': 'xxx',
'type': 'string'
},
'jjj': {
'type': 'string'
},
'kkk': {
'description': 'xxx',
'type': 'string'
},
'lll': {
'description': 'xxx',
'type': 'string'
},
'mmm': {
'description': '',
'type': 'string'
},
'nnn': {
'description': '',
'type': 'array',
'items': {
'$ref': '#/definitions/Categories'
}
}
},
'required': [
'HouseName'
]
},
'HouseCollection': {
'$ref': '#'
}
},
'type': 'object',
'additionalProperties': false,
'properties': {
'houses': {
'description': '',
'type': 'array',
'items': {
'$ref': '#/definitions/House'
}
}
}
}");
string housesJsonString = JsonConvert.SerializeObject(houses);
bool valid = false;
JArray housesJson = JArray.Parse(housesJsonString);
foreach (JObject s in housesJson)
{
IList<string> messages;
valid = housesJson.IsValid(schema, out messages);
}
return valid;
如何更改此代码以一次调用验证方法?当我尝试它时,它在messages
IList中给出了此错误:
How do I alter this code to call the validation method once? When I tried it it gave this error in the messages
IList:
无效的类型.预期的对象,但得到了数组.路径,第1行,位置 1."
Invalid type. Expected Object but got Array. Path ", line1, position 1."
推荐答案
创建对象并将数组放置在其中是解决方案.
Creating an object and placing the array inside it was the solution.
var housesObject = new {
houses = houses
};
string housesJsonString = JsonConvert.SerializeObject(housesObject);
JObject housesJson = JObject.Parse(housesJsonString);
IList < string > messages;
bool valid = housesJson.IsValid(schema, out messages);
return valid;
这篇关于Json.NET针对Schema验证JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!