【发布时间】:2019-12-22 19:00:00
【问题描述】:
我有一些包含 cmets 的 JSON(尽管在 JSON spec 中不严格允许 cmets。)如何使用 System.Text.Json 解析这个 JSON?
我收到的 JSON 如下:
// A person
{
"Id" : 1 /* Person's ID */,
"Name" : "Foo" // Person's name
}
当我尝试将其加载到 JsonDocument 中时:
using var doc = JsonDocument.Parse(jsonString);
我得到以下异常:
System.Text.Json.JsonReaderException: '/' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0. at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes) at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)```
当我尝试使用 JsonSerializer 反序列化时:
var person = JsonSerializer.Deserialize<Person>(jsonString);
我遇到了类似的异常:
System.Text.Json.JsonException: '/' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0. ---> System.Text.Json.JsonReaderException: '/' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0. at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes) at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
如何使用System.Text.Json 解析或反序列化此 JSON?
【问题讨论】:
-
从技术上讲,它不是合法的 JSON,因为官方的 JSON 语法不支持 cmets。尽管如此,大多数 JSON 解析器都支持至少忽略 cmets。
-
同意。使对 cmets 的支持成为非默认选项是明智的,因为它们不在官方语法中。
标签: c# json system.text.json