How can i read json with comment with Json.NET

In order to install an external extension into Google Chrome browser, I try to update chrome external extension json file. Using Json.NET it seems to be easy:

string fileName = "..."; // path to chrome external extension json file

string externalExtensionsJson = File.ReadAllText(fileName);

JObject externalExtensions = JObject.Parse(externalExtensionsJson);


but I get a Newtonsoft.Json.JsonReaderException saying:

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


when calling JObject.Parse because this file contains:

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

{
}

and comments are not part of json (as seen in How do I add comments to Json.NET output?).

I know I can remove comments with a Regex (Regex to remove javascript double slash (//) style comments) but I need to rewrite json into file after modification and keeping comment can be a good thinks.

Question : Is there a way to read json with comments without removing them and be able to rewrite them?


Json.NET only supports reading multi-line JavaScript comments, ie /* commment */

Update: Json.NET 6.0 supports single line comments


A little late but you could always convert single-line comments to multi-line comment syntax before parsing...

something like replace...

.*//.*n

with

$1/*$2*/

...

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

如果你使用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;
}
链接地址: http://www.djcxy.com/p/3394.html

上一篇: “EMALFORMED无法阅读bower.json”“意外标记/”

下一篇: 我如何阅读json与Json.NET的评论