Search code examples
jsonasp.net-corejson.netformatting

How can I remove Indentation in Newtonsoft JSON and ASP.NET Core and add it into settings


I'm supposed to convert our JSON output into canonical JSON.

My 2 questions are:

  1. How do I remove all indentation and whitelines e.g. ?
  2. How do I add those settings to startup.cs ?

My colleague wrote the methods to create the JSON files with the JsonWriter and JsonReader methods from Newtonsoft.

I already overwrote the DefaultContractResolver in a new class to sort the keys alphabetically, but failed to find a proper point in the startup to add those settings. Also I'm missing the option to remove all indentation, new lines etc.

Here is my CanonicalContractResolver:

public class CanonicalContractResolver : DefaultContractResolver
{
    public override JsonContract ResolveContract(Type type)
    {
        var contract = base.CreateContract(type);
            
        // remove Intendation here

        return contract;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList();
    }
}

The afore mentioned JsonReader and JsonWriter classes (that need the canonical JSON output) are linked like this in the Configure method in startup.cs - and I don't really understand where I should add those changes I made in my CanonicalContractResolver class.

services.AddControllers()
            .AddNewtonsoftJson(options => {
                options.SerializerSettings.Converters.Add(new SignaturesConverter());
                options.SerializerSettings.Converters.Add(new PolicyConverter());
            });

I'm a beginner in software engineer and this is my first post on Stackoverflow. I already researched around 6-7 hours in this topic, but the Newtonsoft documentation is very sparse and hasn't helped me a lot.

Thank you all in advance for helping!


Solution

  • You can set the Format property of NewtonsoftJson.

    If you set to Indented:

    services.AddControllers()
                .AddNewtonsoftJson(options => {
                    options.SerializerSettings.Formatting = Formatting.Indented;
                });
    

    Then the output looks like this:

    enter image description here

    If you set to None:

    services.AddControllers()
                    .AddNewtonsoftJson(options => {
                        options.SerializerSettings.Formatting = Formatting.None;
                    });
    

    Then the output looks like this: enter image description here