Richard Schneider Richard Schneider - 3 months ago 19
JSON Question

Generating newlines instead of CRLFs in Json.Net

For my unix/java friends I would like to send newlines ('\n') instead of a CRLF (
'\r\n') in Json.Net. I tried setting a StreamWriter to use a newline without any success.

I think Json.Net code is using

Environment.NewLine
instead of calling
TextWriter.WriteNewLine()
. Changing
Environment.NewLine
is not an option because I'm running as a server and the newline encoding is based on the request.

Is there some other way to force newline for crlf?

Here's my code -

using (var streamWriter = new StreamWriter(writeStream, new UTF8Encoding(false))
{
NewLine = "\n"
})
using (var jsonWriter = new JsonTextWriter(streamWriter)
{
CloseOutput = true,
Indentation = 2,
Formatting = Formatting.Indented
})
{
// serialise object to JSON
}

Answer

If you want to customize indentation whitespace, just override JsonTextWriter.WriteIndent:

public class JsonTextWriterEx : JsonTextWriter
{
    public string NewLine { get; set; }

    public JsonTextWriterEx (TextWriter textWriter) : base(textWriter)
    {
        NewLine = Environment.NewLine;
    }

    protected override void WriteIndent ()
    {
        if (Formatting == Formatting.Indented) {
            WriteWhitespace(NewLine);
            int currentIndentCount = Top * Indentation;
            for (int i = 0; i < currentIndentCount; i++)
                WriteIndentSpace();
        }
    }
}
Comments