如何使用 Json.NET 读取带注释的 JSON 内容?

问题描述 投票:0回答:4

为了将外部扩展安装到 Google Chrome 浏览器中,我尝试更新 Chrome 外部扩展 JSON 文件。使用

Json.NET
看起来很简单:

string fileName = "..."; // Path to a Chrome external extension JSON file

string externalExtensionsJson = File.ReadAllText(fileName);

JObject externalExtensions = JObject.Parse(externalExtensionsJson);


但我得到一个

Newtonsoft.Json.JsonReaderException
说:

"Error parsing comment. Expected: *, got /. Path '', line 1, position 1."


调用

JObject.Parse
时,因为此文件包含:

// This JSON file will contain a list of extensions that will be included
// in the installer.

{
}

并且注释不是 JSON 的一部分(如如何向 Json.NET 输出添加注释?中所示)。

我知道我可以使用正则表达式删除注释(正则表达式删除JavaScript双斜杠(//)样式注释),但我需要在修改后将JSON重写到文件中并保留注释可能是一件好事.

有没有一种方法可以读取带注释的 JSON 内容而不删除它们并能够重写它们?

c# json.net
4个回答
58
投票

Json.NET 仅支持读取多行 JavaScript 注释,即 /* 注释 */

更新: Json.NET 6.0 支持单行注释


4
投票

如果您坚持使用 JavaScriptSerializer(来自 System.Web.Script.Serialization 命名空间),我发现这足够好......

private static string StripComments(string input)
{
    // JavaScriptSerializer doesn't accept commented-out JSON,
    // so we'll strip them out ourselves;
    // NOTE: for safety and simplicity, we only support comments on their own lines,
    // not sharing lines with real JSON

    input = Regex.Replace(input, @"^\s*//.*$", "", RegexOptions.Multiline);  // removes comments like this
    input = Regex.Replace(input, @"^\s*/\*(\s|\S)*?\*/\s*$", "", RegexOptions.Multiline); /* comments like this */

    return input;
}

3
投票

在解析之前,您始终可以将单行注释转换为多行注释语法...

比如更换...

.*//.*\n

$1/*$2*/

...

Regex.Replace(subjectString, ".*//.*$", "$1/*$2*/");

0
投票

我使用 JsonSerializer.Deserialize 来完成此操作。

var options = new JsonSerializerOptions(); options.ReadCommentHandling = JsonCommentHandling.Skip; var data = JsonSerializer.Deserialize<JsonDocument>(fileData, options);

© www.soinside.com 2019 - 2024. All rights reserved.