如何通过Json.NET评论阅读json

时间:2012-04-25 13:43:54

标签: c# json.net

要在Google Chrome浏览器中安装外部扩展程序,我会尝试更新chrome外部扩展程序json文件。使用Json.NET似乎很容易:

string fileName = "..."; // path to 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的一部分(如How do I add comments to Json.NET output?中所示)。

我知道我可以用正则表达式(Regex to remove javascript double slash (//) style comments)删除注释但是我需要在修改后将json重写到文件中并保持注释可以是一个很好的思考。

问题:有没有办法在不删除注释的情况下读取带有注释的json并能够重写它们?

3 个答案:

答案 0 :(得分:45)

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

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

答案 1 :(得分:4)

If you are stuck with JavascriptSerializer (from the System.Web.Script.Serialization namespace), I have found that this works good enough...

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;
}

答案 2 :(得分:3)

稍晚但你总是可以在解析之前将单行注释转换为多行注释语法...

像替换......

.*//.*\n

$1/*$2*/

...

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