【发布时间】:2021-08-11 20:57:01
【问题描述】:
我有一个经常监控 .json 文件结构的 Windows 服务,它一直正常工作,直到昨天我们的应用程序无法正确读取这个 .json 但被认为是有效的!:
{
"infohead": {
"indicator": "12",
"istesting": "ABC_12_219",
"isdate": "2021-08-11 10:02:12"
},
"headers": {
"url": "https://www.blahblah.com/"
},
"advertisements": [,
{
"type": "arc",
"adType": "1",
"appn": {
"x": 1241,
"y": 1241,
"z": 1243,
}
},
{
"type": "arc2",
"adType": "1",
"appn": {
"x": 1441,
"y": 1441,
"z": 1443,
}
}
]
}
如果它在浏览器中加载,我会收到错误:
语法错误:JSON.parse:第 10 行第 21 列的意外字符 JSON 数据
C# 以某种方式检测到这是正确的,数组“advertisements”具有三个对象,一个具有空值,另一个具有值。
"advertisements": [,
{
"type": "arc",
"adType": "1",
"appn": {
"x": 1241,
"y": 1241,
"z": 1243,
}
},
{
"type": "arc2",
"adType": "1",
"appn": {
"x": 1441,
"y": 1441,
"z": 1443,
}
}
]
我也使用了这个问题中描述的方法,
How to make sure that string is valid JSON using JSON.NET
我不想使用 JSON 架构 (Validate Json schema C#) 进行验证,还有其他解决方案来执行验证吗?
【问题讨论】:
-
Json.NET 可以容忍某些类型的畸形 JSON。见Support "strict mode" for RFC7159 parsing #646:你有没有列出Json.Net更宽松的所有方式的列表? 在我的脑海中:...空逗号,例如
[,,,] -
System.Text.Json 默认情况下是完全无情的。如果您只想检查 JSON 格式是否正确,请尝试加载到
JsonDocument或使用TrySkip()使用Utf8JsonReader读取它,如图所示 here。