I'm supposed to convert our JSON output into canonical JSON.
My 2 questions are:
- How do I remove all indentation and whitelines e.g. ?
- 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!
CodePudding user response:
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:
If you set to None:
services.AddControllers()
.AddNewtonsoftJson(options => {
options.SerializerSettings.Formatting = Formatting.None;
});


