-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
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.