Console.WriteLine($"Failed schema resource base uri: {validationResult.SchemaResourceBaseUri}");
}
复制代码
输出信息
当json数据验证失败后,可以查看错误数据的具体信息:
IsValid: As summary indicator for passed validation or failed validation.
ResultCode: The specific error type when validation failed.
ErrorMessage: the specific wording for human readable message
Keyword: current keyword when validation failed
InstanceLocation: The location of the JSON value within the instance being validated. The value is a JSON Pointer.
RelativeKeywordLocation: The relative location of the validating keyword that follows the validation path. The value is a JSON Pointer, and it includes any by-reference applicators such as "$ref" or "$dynamicRef". Eg:
/properties/width/$ref/minimum
复制代码
SubSchemaRefFullUri: The absolute, dereferenced location of the validating keyword when validation failed. The value is a full URI using the canonical URI of the relevant schema resource with a JSON Pointer fragment, and it doesn't include by-reference applicators such as "$ref" or "$dynamicRef" as non-terminal path components. Eg:
[Keyword("customKeyword")] // It is your custom keyword name
[JsonConverter(typeof(CustomKeywordJsonConverter))] // Use 'CustomKeywordJsonConverter' to deserialize to 'CustomKeyword' instance out from json schema text
internal class CustomKeyword : KeywordBase
{
private readonly string _customValue; // Simple example value
: ValidationResult.CreateFailedResult(ResultCode.UnexpectedValue, "It is not my expected value.", options.ValidationPathStack, Name, instance.Location);
}
}
复制代码
internal class CustomKeywordJsonConverter : JsonConverter<CustomKeyword>
{
// Library will input json value of your custom keyword: "customKeyword" to this method.
public override CustomKeyword? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Briefly:
return new CustomKeyword(reader.GetString()!);
}
public override void Write(Utf8JsonWriter writer, CustomKeyword value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
复制代码
Format支持
目前library支持如下format:
uri
uri-reference
date
time
date-time
email
uuid
hostname
ipv4
ipv6
json-pointer
regex
Format 验证需要显式enable, 当验证数据时,请传入配置好的 JsonSchemaOptions:
jsonValidator.Validate(instance, new JsonSchemaOptions{ValidateFormat = true});
复制代码
如果需要自定义format验证,可以实现一个FormatValidator子类并注册:
[Format("custom_format")] // this is your custom format name in json schema
public class TestCustomFormatValidator : FormatValidator