How can i read json with comment with Json.NET
为了在Google Chrome浏览器中安装外部扩展,我尝试更新chrome外部扩展json文件。使用
1 2 3 4 5 | string fileName ="..."; // path to chrome external extension json file string externalExtensionsJson = File.ReadAllText(fileName); JObject externalExtensions = JObject.Parse(externalExtensionsJson); |
但我得到一个
1 | "Error parsing comment. Expected: *, got /. Path '', line 1, position 1." |
调用
1 2 3 4 5 | // This json file will contain a list of extensions that will be included // in the installer. { } |
注释不是JSON的一部分(如如何将注释添加到json.net输出中所示?).
我知道我可以用regex删除注释(regex删除javascript双斜杠(//)样式的注释),但是我需要在修改后将json重写到文件中,保留注释是个不错的主意。
问题:有没有一种方法可以在不删除注释的情况下读取JSON,并且能够重写它们?
json.net只支持读取多行javascript注释,即/*命令*/
更新:json.net 6.0支持单行注释
如果您一直使用javascriptserializer(来自system.web.script.serialization命名空间),我发现这已经足够好了…
1 2 3 4 5 6 7 8 9 10 11 12 | 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; } |
有点晚了,但在解析之前,您可以将单行注释转换为多行注释语法…
类似于替换…
1 | .*//.* |
具有
1 | $1/*$2*/ |
…
1 | Regex.Replace(subjectString,".*//.*$","$1/*$2*/"); |