【发布时间】:2017-05-23 13:27:13
【问题描述】:
我正在使用 Json 模式来验证 json 对象。我正确收到错误消息。但它看起来更像是对开发人员友好的错误消息。有什么方法可以自定义错误消息,以便我可以使其更加用户友好。我查了很多论坛都找不到解决办法。
下面是我使用的代码:
string Json = @"{'Sheet1':[{'Location':'#$','First Name':11,'Last Name':'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA','Amount':'A','Date of Birth':'8522/85/25'}]}";
string JSONSchemaValidator = @"{'$schema':'http://json-schema.org/draft-04/schema#','title':'JSON Validation Schema','type':'object','additionalProperties':true,'properties':{'Sheet1':{'type':'array','items':{'type':'object','additionalProperties':true,'properties':{'Location':{'type':['number','string','null'],'pattern':'^[a-zA-Z0-9\\-\\s]+$','maxLength':15},'First Name':{'type':['string','null'],'maxLength':20,'pattern':'^[a-zA-Z\\-\\s]+$'},'Last Name':{'type':['string','null'],'maxLength':10,'pattern':'^[a-zA-Z\\-\\s]+$'},'Amount':{'type':['number','null'],'minimum':-999999999.99,'maximum':999999999.99,'exclusiveMaximum':true,'multipleOf':0.01},'Date of Birth':{'type':['string','null'],'format':'date-time'}}}}}}";
JSchema schema = JSchema.Parse(JSONSchemaValidator);
JObject person = JObject.Parse(Json);
IList<string> iJSONSchemaValidatorErrorList;
bool valid = person.IsValid(schema, out iJSONSchemaValidatorErrorList);
if (iJSONSchemaValidatorErrorList != null && iJSONSchemaValidatorErrorList.Count > 0)
{
foreach (string error in iJSONSchemaValidatorErrorList)
{
Console.WriteLine(error);
}
}
Console.ReadKey();
以下是我收到的错误消息:
1. String '#$' does not match regex pattern '^[a-zA-Z0-9\-\s]+$'. Path 'Sheet1[0].Location', line 1, position 27.
2. Invalid type. Expected String, Null but got Integer. Path 'Sheet1[0]['First Name']', line 1, position 43.
3. String 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' exceeds maximum length of 10. Path 'Sheet1[0]['Last Name']', line 1, position 87.
4. Invalid type. Expected Number, Null but got String. Path 'Sheet1[0].Amount', line 1, position 100.
5. String '8522/85/25' does not validate against format 'date-time'. Path 'Sheet1[0]['Date of Birth']', line 1, position 129.
我正在寻找类似的东西:
1. 'Location' in Column 1 of Sheet1 should be alphanumeric.
2. 'Name' in Column 1 of Sheet1 should only contain alphabets.
3. 'Last Name' in column 1 exceeds maximum length of 10.
4. 'Amount' in column 1 should contain only numbers.
5. 'Date of Birth' in column 1 is not a valid date.
【问题讨论】:
-
我遇到了与此完全相同的问题。如果我找到解决方案,将在此处发布。目前,我已经编写了自己的类,针对我正在使用的特定模式进行了定制,这些类对 Json-Schema-Validator 返回的错误数据执行特定检查,并返回更用户友好的错误消息版本.我正在考虑为此开始使用我自己的可能的开源验证库。
标签: c# json jsonschema json-schema-validator