How can I read JSON content with a comment with Json.NET?

后端 未结 3 1320
星月不相逢
星月不相逢 2020-12-17 07:47

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

3条回答
  •  感动是毒
    2020-12-17 08:04

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

提交回复
热议问题