【发布时间】:2020-09-24 07:58:39
【问题描述】:
我收到以 JSON 值开头的字符串内容(可以是简单的也可以是复杂的),然后包含一些附加内容。我希望能够解析 JSON 文档。
我无法控制字符串,因此我无法在 JSON 内容之后放置任何类型的分隔符,以便我将其隔离。
例子:
"true and some more" - yields <true>
"false this is different" - yields <false>
"5.6/7" - yields <5.6>
"\"a string\""; then this" - yields <"a string">
"[null, true]; and some more" - yields <[null, true]>
"{\"key\": \"value\"}, then the end" - yields <{"key": "value"}>
问题在于尾随内容。解析器期望输入结束并抛出异常:
')' is invalid after a single JSON value. Expected end of data.
JsonDocumentOptions 中没有允许尾随内容的选项。
作为奖励,如果你能给出一个使用 ReadOnlySpan<char> 的解决方案,那就太棒了。
【问题讨论】:
-
您可以通过
CheckAdditionalContent设置使用json.net 执行此操作,请参阅Discarding garbage characters after json object with Json.Net。不过,system.text.json 中没有内置任何内容来执行此操作。也许Utf8JsonStreamReader从 this answer 到 Parsing a JSON file with .NET core 3.0/System.text.Json 可能会满足您的需求,可能需要适当的调整... -
嗯,
Utf8JsonStreamReader从 this answer 到 Parsing a JSON file with .NET core 3.0/System.text.Json by mtosh 实际上按原样工作!见dotnetfiddle.net/o9Ctba。其实真的没想到。标记为重复,还是添加为答案? -
您不能使用
System.Text.Json从ReadOnlySpan<char>反序列化,但您只能从字节跨度、序列或流中反序列化。这是因为它被设计为直接从 Utf8 字节序列反序列化,而不是 char 序列。 -
这在fiddle 中显示。只需反序列化为
JsonElement:jsonStreamReader.Deserialize<JsonElement>(), -
我弄清楚了为什么您的测试用例有效:它们都使用有效的 JSON 字符(
/对 cmets 有效)。如果您添加的测试用例包含对 JSON 无效的字符,例如+、_、)或g,测试失败。 (不知道为什么;有效。)......也许。:也打破了它。
标签: json parsing system.text.json