利用JSON模式校验JSON
Json.NET通过JsonSchema类和 JsonValidatingReader类来支持JSON模式标准。它位于Newtonsoft.Json.Schema命名空间中。
JSON模式用来校验JSON片段的结构和数据类型,类似于XML模式对于XML。你可以在此处读取JSON模式:json-schema.org
Note |
---|
过时! JSON模式校验已经被移到它自己的包里了。请参阅https://www.newtonsoft.com/jsonschema以了解细节。 |
利用JSON模式校验JSON
检查JSON是否有效的最简单方法是把JSON加载到一个JObject或JArray中,然后使用IsValid(JToken, JsonSchema)方法配合JSON模式。
利用IsValid校验JSON
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
若要获得校验错误消息,请使用IsValid(JToken, JsonSchema, IList<String> )重载或Validate(JToken, JsonSchema, ValidationEventHandler)重载。
利用IsValid校验JSON
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.
IsValid内在地使用JsonValidatingReader来实施JSON模式校验。若要跳过把JSON载入到JObject/JArray中的开销,请校验JSON,然后把JSON反序列化为类,可以在反序列化对象的时候,使用JsonValidatingReader配合JsonSerializer来校验JSON。
利用JsonValidatingReader校验JSON
string json = @"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
validatingReader.Schema = JsonSchema.Parse(schemaJson);
IList<string> messages = new List<string>();
validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);
JsonSerializer serializer = new JsonSerializer();
Person p = serializer.Deserialize<Person>(validatingReader);
创建JSON模式
获得JsonSchema对象的最简单方法是从一个字符串或文件中载入它。
从字符串或文件创建JSON模式
// load from a string
JsonSchema schema1 = JsonSchema.Parse(@"{'type':'object'}");
// load from a file
using (TextReader reader = File.OpenText(@"c:\schema\Person.json"))
{
JsonSchema schema2 = JsonSchema.Read(new JsonTextReader(reader));
// do stuff
}
也可以在代码中创建JsonSchema对象。
在代码是创建新的JSON
JsonSchema schema = new JsonSchema();
schema.Type = JsonSchemaType.Object;
schema.Properties = new Dictionary<string, JsonSchema>
{
{ "name", new JsonSchema { Type = JsonSchemaType.String } },
{
"hobbies", new JsonSchema
{
Type = JsonSchemaType.Array,
Items = new List<JsonSchema> { new JsonSchema { Type = JsonSchemaType.String } }
}
},
};
JObject person = JObject.Parse(@"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
// true