.netjsonminify

Minify a json string using .NET


How can an existing json string be cleaned up/minfied? I've seen regexes being used. Any other (maybe more efficient) approach?


Solution

  • Install-Package Newtonsoft.Json
    

    Just parse it and then serialize back into JSON:

    var jsonString = "  {  title: \"Non-minified JSON string\"  }  ";
    var obj = JsonConvert.DeserializeObject(jsonString);
    jsonString = JsonConvert.SerializeObject(obj);
    

    SerializeObject(obj, Formatting.None) method accepts Formatting enum as a second parameter. You can always choose if you want Formatting.Indented or Formatting.None.