错误json:错误值 -2146.379
[{
"Key": "surface_heights_average",
"Value": "-2122.739nm",
"Description": "surface_heights_average"
}, {
"Key": "surface_heights_max",
"Value": "-2105.69nm",
"Description": "surface_heights_max"
}, {
"Key": "surface_heights_min",
"Value": "-2146.165nm",
"Description": "surface_heights_min"
}, {
"Key": "hole_heights_average",
"Value": "-2092.042nm",
"Description": "hole_heights_average"
}, {
"Key": "hole_heights_max",
"Value": "-2075.576nm",
"Description": "hole_heights_max"
}, -2146.379, {
"Key": "hole_depths_average",
"Value": "-30.697nm",
"Description": "hole_depths_average"
}
]
发现 Newtonsoft.Json 不能正常校验出json异常,除非反序列化到具体的实体类,使用Json Schema 可以正常校验异常位置
一、Newtonsoft.Json 反序列化校验
public bool IsValidJson(string jsonString)
{
try
{
var obj = JsonConvert.DeserializeObject(jsonString);
//var obj = JObject.Parse(jsonString);
return true;
}
catch (JsonReaderException)
{
return false;
}
}
不能正确校验异常
二、Json Schema 校验
nuget包:NJsonSchema
string json = @"[{
""Key"": ""surface_heights_average"",
""Value"": ""-2122.739nm"",
""Description"": ""surface_heights_average""
}, {
""Key"": ""surface_heights_max"",
""Value"": ""-2105.69nm"",
""Description"": ""surface_heights_max""
}, {
""Key"": ""surface_heights_min"",
""Value"": ""-2146.165nm"",
""Description"": ""surface_heights_min""
}, {
""Key"": ""hole_heights_average"",
""Value"": ""-2092.042nm"",
""Description"": ""hole_heights_average""
}, {
""Key"": ""hole_heights_max"",
""Value"": ""-2075.576nm"",
""Description"": ""hole_heights_max""
}, -2146.379, {
""Key"": ""hole_depths_average"",
""Value"": ""-30.697nm"",
""Description"": ""hole_depths_average""
}
]
";
var schema = JsonSchema.FromSampleJson(json);
var errors = schema.Validate(json);
foreach (var error in errors)
Console.WriteLine($"json异常: 行号:{error.LineNumber} 位置:{error.LinePosition}");
output:
能正常校验json异常