Skip to content

[API Proposal]: Add the ability to specify line endings when serializing Json #84117

@aodpi

Description

@aodpi

Background and motivation

Currently when serializing Json you have the option to write it Indented. But the new line character seems to be picked up based on the operating system through Environment.NewLine. This is fair but I've encountered a situation when a client wanted Line endings to be Line Feed character ('\n') instead of Carriage Return and Line Feed (\r\n). Proposal is to add the option to specify the line ending character to be used when serializing json with indentation.

When using popular package Newtonsoft.Json you have the ability to pass a StreamWriter instance which will be used to write json, with an additional ability to specify the NewLine Character when instantiating a StreamWriter

API Proposal

Extend JsonSerializerOptions and give users ability what line terminator to use when writing Indented json so we would have:

namespace System.Text.Json;

public partial class JsonSerializerOptions
{
    public bool WriteIndented { get; set; }
    public char IndentChar { get; set; }
    public int IndentSize { get; set; }
+   public string NewLine { get; set; } = Environment.NewLine; // only "\n" or "\r\n" are permitted values.

public partial struct JsonWriterOptions
{
    public bool Indented { get; set; }
    public char IndentChar { get; set; }
    public int IndentSize { get; set; }
+   public string NewLine { get; set; } = Environment.NewLine; // only "\n" or "\r\n" are permitted values.
}

By default the NewLine property will have the line terminator based on the current OS as it's treated at the moment.

API Usage

User would initialize JsonSerializerOptions by specifying the line terminator

var jsonOptions = new JsonSerializerOptions
{
    WriteIndented = true,
    NewLine = "\n"
};

User would pass these options when serializing json as follows:

using System.Text.Json;

JsonSerializer.Serialize(stream, value, jsonOptions);

The result would be a json string serialized with specified line terminator written to the specified stream.

Alternative Designs

No response

Risks

No identified risks or breaking changes.

Metadata

Metadata

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Text.Jsonhelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is mergedpartner-impactThis issue impacts a partner who needs to be kept updated

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions