【发布时间】:2017-09-05 20:15:47
【问题描述】:
我已经在这里看到了很多问题 here 和 here 但仍然无法进行以下工作。
对于 ex.Message 中的这些响应中的任何一个:
响应 1
[
{
"validationErrorType": "WrongType",
"message": "Validation error of type WrongType",
"errorType": "ValidationError"
}
]
响应 2
[
{
"message": "Validation error of type WrongType:",
"errorType": "ValidationError"
}
]
我正在尝试如下动态解析:
JArray parsedJObject = JArray.Parse(ex.Message);
JSchema oldSchema = JSchema.Parse(@"
{
'type': 'array',
'properties': {
'message': {'type': 'string'},
'errorType': {'type': 'string'}
},
'additionalProperties': false
}");
JSchema graphQlSchema = JSchema.Parse(@"
{
'type': 'array',
'properties': {
'validationErrorType': {'type': 'string'},
'message': {'type': 'string'},
'errorType': {'type': 'string'}
},
'additionalProperties': false
}");
if (parsedJObject.IsValid(oldSchema)) // IsValid - 1
{
// Do stuff
}
else if (parsedJObject.IsValid(graphQlSchema)) // IsValid - 2
{
// Do stuff
}
但是,对于任一响应,两个 IsValid() 调用都返回 true。我在这里做错了什么?
对于响应 1,我希望 IsValid - 1 返回 true 和 IsValid - 2 返回 false
对于响应 2,我希望 IsValid - 1 返回 false 和 IsValid - 2 返回 true
更新
按照David Kujawski 和dbc 的建议循环遍历JArray 并添加required 属性,我已经取得了进展。
我的更新代码如下,但仍在努力使用嵌套的 locations 对象验证架构。
回应
[
{
"validationErrorType": "WrongType",
"locations": [
{
"line": 4,
"column": 1
}
],
"message": "Validation error of type WrongType",
"errorType": "ValidationError"
}
]
架构定义:
JSchema graphQlSchema = JSchema.Parse(@"
{
'type': 'object',
'properties':
{
'validationErrorType': {'type': 'string'},
'locations':
{
'type': 'object',
'properties':
{
'line': {'type': 'string'},
'column': {'type': 'string'}
}
},
'message': {'type': 'string'},
'errorType': {'type': 'string'}
},
'additionalProperties': false,
'required': ['message', 'errorType', 'validationErrorType', 'locations']
}");
解析响应
JArray parsedJObject = JArray.Parse(ex.Message);
foreach (JToken child in parsedJObject.Children())
{
if (child.IsValid(graphQlSchema)) // Not resolving to true
{
var graphQlSchemaDef = new[]
{
new
{
validationErrorType = string.Empty,
locations = new
{
line = string.Empty,
column = string.Empty
},
message = string.Empty,
errorType = string.Empty
}
};
var exceptionMessages = JsonConvert.DeserializeAnonymousType(ex.Message, graphQlSchemaDef);
foreach (var message in exceptionMessages)
{
// Do stuff
}
}
}
【问题讨论】:
-
它们很相似。只有 validationErrorType 可以为 null
-
我不明白你的意思。你能澄清一下吗?
-
属性validationErrorType为字符串,字符串为引用类型,可以为null
-
一个包含所有 3 个属性的具体类就足够了。 validationErrorType 有时会为空。
-
对于
graphQlSchema,请尝试根据需要标记validationErrorType,如spacetelescope.github.io/understanding-json-schema/reference/…所示。 Json,NET 架构似乎支持这一点,如文档所示:newtonsoft.com/jsonschema/help/html/…
标签: c# json jsonschema