-1

I am using .NET Core 3.1 with System.Text.Json I am reading JSON from file

var jsonFilename = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "WellKnownConfig.json");
if (System.IO.File.Exists(jsonFilename))
{
    var fileContent = System.IO.File.ReadAllText(jsonFilename);
    if (!string.IsNullOrWhiteSpace(fileContent))
    {
         //var o = JsonDocument.Parse(fileContent);                        
         Result = new OkObjectResult(fileContent);
    }
    else
    {
        Result = new NoContentResult();
    }
}

The problem is it is having whitespaces. anyway, I can remove white spaces without string parsing. Like some way from System.Text.Json by loading into some object while using JsonDocument or JsonSerializer

Also is there some way I can minify this JSON after loading it from file

I have seen some solution for newtonjson

Minify a json string using .NET

Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93

1 Answers1

0

Following Did the trick. I hope it will help other's as well

var fileContent = System.IO.File.ReadAllText(jsonFilename);
if (!string.IsNullOrWhiteSpace(fileContent) && Utility.IsValidJson(fileContent))
{
    var obj = JsonSerializer.Deserialize<object>(fileContent);
    Result = new OkObjectResult(obj);
}
else
{
    Result = new NoContentResult();
}
live2
  • 3,771
  • 2
  • 37
  • 46
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93
  • That's what you said you *didn't* want to do. It's also what your code already did halfway - parse the JSON string. If it *returned* the parsed object, you'd get an unindented string back – Panagiotis Kanavos Feb 14 '20 at 12:33
  • 1
    Since you want to unindent, the low-cost solution would be to read tokens one at a time with a Utf8JsonReader and write it out with a Utf8JsonWriter. This would avoid caching the entire object in memory, which is the typical reason people want to avoid parsing – Panagiotis Kanavos Feb 14 '20 at 12:38
  • @PanagiotisKanavos may be i have not explain it clearly but this was the thing i wnated to do. haven't used Utf8JsonReader but will google about it. Thanks – Kamran Shahid Feb 14 '20 at 12:45