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
}
In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.
JSON strings do not allow real newlines in its data; it can only have escaped newlines. Snowflake allows escaping the newline character by the use of an additional backslash character.
Full JSON grammar The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.
I see several solutions here that are configuring the serializer. But if you want quick and dirty, just replace the characters with what you want. After all, JSON is just a string.
string json = JsonConvert.SerializeObject(myObject);
json = json.Replace("\r\n", "\n");
I know this is an old question but I had a hard time getting the accepted answer to work and maintain proper indented formatting. As a plus, I am also not creating an override to make this work.
Here is how I got this to work correctly:
using (var writer = new StringWriter())
{
writer.NewLine = "\r\n";
var serializer = JsonSerializer.Create(
new JsonSerializerSettings
{
Formatting = Formatting.Indented
});
serializer.Serialize(writer, data);
// do something with the written string
}
I am assuming that the code changes referenced in this question enabled the setting of NewLine
on the StringWriter
to be respected by the serializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With