Creating new lines instead of CRLF in Json.Net

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

I think the Json.Net code uses Environment.NewLine instead of calling TextWriter.WriteNewLine() . Changing Environment.NewLine not an option, because I work as a server, and the encoding of the new line is based on the request.

Is there any other way to force a newline for crlf?

Here is 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 } 
+7
json c #
source share
5 answers

If you want to customize the indentation firmware, 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(); } } } 
+5
source share

After delving into the Json.Net code, I see that the problem is with the JsonTextWriter.WriteIndent , thanks to Athari .

Instead of _writer.Write(Environment.NewLine); it should be _writer.WriteLine(); .

I sent a transfer request to github. https://github.com/JamesNK/Newtonsoft.Json/pull/271

+7
source share

Here I see several solutions that configure 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"); 
+2
source share

In a wired protocol, almost always there is a line ending with crlf. If you feel that you really need to do this, post-processing is the way that you need to write - write it to a string, and then change the string before returning it.

Please note that this is a lot of additional processing for what I consider to be actual negative. Not recommended.

+1
source share

I know this is an old question, but it was difficult for me to get an accepted answer to the work and to maintain the correct formatting of the indentation. As a plus, I also don't create an override to do the job.

Here is how I got it 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 assume that the changes> code provided in this question allowed the NewLine parameter on StringWriter comply with the serializer.

0
source share

All Articles