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

Mui*_*ota 37 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);
Run Code Online (Sandbox Code Playgroud)


但我得到一个Newtonsoft.Json.JsonReaderException说法:

"Error parsing comment. Expected: *, got /. Path '', line 1, position 1." 
Run Code Online (Sandbox Code Playgroud)


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

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

{
}
Run Code Online (Sandbox Code Playgroud)

和注释不是json的一部分(如何在Json.NET输出中添加注释?).

我知道我可以用正则表达式删除注释(正则表达式删除javascript双斜杠(//)样式注释)但我需要在修改后将json重写到文件中并保持评论可能是一个很好的想法.

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

Jam*_*ing 48

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

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

  • 谢谢,但我别无选择:谷歌浏览器提供了一个名为"external_extensions.json"的文件,其中包含单行注释,我必须完成它.更一般地,Json经常用作配置文件,其中用户可以添加注释(单行和/或多行).我们别无选择:我们可以面对阅读每条评论的需要(理想情况下重写它).我喜欢能够使用Json.Net来做到这一点.你认为这可能是一种可能的演变吗? (2认同)