JSON conventions and defaults

Look at the output below;

[{"levelId":1,"levelName":"Team","levelEnum":"Team","hasSave":true,"hasReset":true,"hasDelete":true,"hasGeneratePDF":false},{"levelId":2,"levelName":"Finance","levelEnum":"Finance","hasSave":true,"hasReset":true,"hasDelete":false,"hasGeneratePDF":false}]

This JSON is basically a serialization of our entity, with some built-in conventions such as;

  • CamelCase instead of PascalCase: We got levelName instead of LevelName and son, meaning that all our PascalCase .NET class names and properties will be automatically converted into camelCase when they are serialized to JSO,
  • No indentation and no line feed / carriage return (LF/CR): Everything is stacked within a single line of text.

These conventions are the default options set by .NET core when dealing with JSON outputs.

To change the default behavior for readability and no PascalCase to CamelCase switching, add these to Program.cs file;

builder.Services.AddControllersWithViews()
    .AddJsonOptions(options =>
    {
        // set this option to TRUE to indent hte JSON output
        options.JsonSerializerOptions.WriteIndented = true;
        // set this option to NULL to use PascalCase instead of camelCase (default)
        options.JsonSerializerOptions.PropertyNamingPolicy = null;
    });

Now the output would look like this;

[
  {
    "LevelId": 1,
    "LevelName": "Team",
    "LevelEnum": "Team",
    "HasSave": true,
    "HasReset": true,
    "HasDelete": true,
    "HasGeneratePDF": false
  },
  {
    "LevelId": 2,
    "LevelName": "Finance",
    "LevelEnum": "Finance",
    "HasSave": true,
    "HasReset": true,
    "HasDelete": false,
    "HasGeneratePDF": false
  }
]

Looks great.

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect