Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating newlines instead of CRLFs in Json.Net

Tags:

json

c#

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
}
like image 223
Richard Schneider Avatar asked May 11 '14 01:05

Richard Schneider


People also ask

How do I handle newlines in 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.

Can JSON have new line character?

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.

Can JSON contain carriage return?

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.


2 Answers

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");
like image 85
mason Avatar answered Sep 22 '22 05:09

mason


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.

like image 39
Ryan Butcher Avatar answered Sep 24 '22 05:09

Ryan Butcher