44

为了将外部扩展安装到 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 输出添加注释?)。

我知道我可以使用正则表达式删除评论(Regular expression to remove JavaScript double slash (//) style comments),但我需要在修改后将 JSON 重写到文件中,保留评论可能是一件好事。

有没有办法在不删除评论的情况下读取带有评论的 JSON 内容并能够重写它们?

4

3 回答 3

56

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

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

于 2012-04-25T23:54:18.800 回答
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;
}
于 2015-07-28T15:36:40.933 回答
3

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

类似换...

.*//.*\n

$1/*$2*/

...

Regex.Replace(subjectString, ".*//.*$", "$1/*$2*/");
于 2013-05-13T00:12:22.000 回答