Skip to content

[API Proposal]: Allow specifying indent size and whitespace character when writing JSON with Utf8JsonWriter #63882

Closed
@noqn

Description

@noqn

Background and motivation

This proposal would enable Utf8JsonWriter to write indented JSON with either spaces or tabs, and with a variable number of whitespace characters per indentation.

To preface, indentation size was brought up around two years ago in #1174. Although the area owners were open for input, there were little discussion at the time and the issue was closed. Now that more eyes are on System.Text.Json I am hoping to revisit the topic.


As is well known, people form strong opinions about indentation. In a context where the serialized JSON will be inspected or manually edited by the users, there will inevitably be a demand for the application to conform to their indentation preferences. Adding this functionality to System.Text.Json would in turn let application developers provide indentation settings to their users.

This would also be useful for when the serialized JSON must match the indentation of the source files which were deserialized e.g., for version control purposes.

API Proposal

namespace System.Text.Json
{
    public sealed class JsonSerializerOptions 
    {
        public char IndentCharacter { get; set; }
        public int IndentSize { get; set; }
    }
    
    public struct JsonWriterOptions 
    {
        public char IndentCharacter { get; set; }
        public int IndentSize { get; set; }
    }
}

IndentCharacter would define which whitespace character is used and IndentSize would define the number of whitespace characters that would be written per indentation level.

To match the behavior of JsonWriterOptions.MaxDepth, the default values of IndentCharacter ('\0') and IndentSize (0) would represent fallback values (which would be properly assigned in the Utf8JsonWriter constructor).

API Usage

var jsonWriterOptions = new JsonWriterOptions() 
{
    Indented = true,
    IndentCharacter = '\t',
    IndentSize = 1
};

var jsonSerializerOptions = new JsonSerializerOptions()
{
    WriteIndented = true,
    IndentSize = 4
};

Alternative Designs

For the sake of comparison, this is how Json.NET does it:

namespace Newtonsoft.Json 
{
    public class JsonTextWriter ...
    {
        public int Indentation { get; set; }
        public char IndentChar { get; set; }
    }
}

Json.NET's Indentation property combines the behavior of Indented and IndentSize by using the default value of 0 to disable formating altogether. Such a solution would however clash with our current API.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions