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

后端 未结 3 1305
星月不相逢
星月不相逢 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;
    }
    
    0 讨论(0)
  • 2020-12-17 08:13

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

    Update: Json.NET 6.0 supports single line comments

    0 讨论(0)
  • 2020-12-17 08:22

    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*/");
    
    0 讨论(0)
提交回复
热议问题