Why is JSON.NET serializing everything in one line?

I just want the JSON.net serializer to write JSON objects (to a file), one object per line , but instead it just adds everything to the same top line. All JSON.net samples seem to imply that what I want is the default behavior, but I don’t see it working that way. Here is the code:

static void EtwToJsonHelper(TraceEvent data, JsonSerializer s, JsonTextWriter jw) { var names = data.PayloadNames; jw.WriteStartObject(); jw.WritePropertyName("TimeStamp"); jw.WriteValue(data.TimeStamp); ... jw.WriteEndObject(); } 

The result is as follows: {object} {obj2} ... {objN} all on one line.

But I want:

{obj1}

{obj2}

...

How to do it?

+6
source share
2 answers

Presented samples are indented for clarity, but the default behavior is to write the resulting JSON string without extra spaces. You can override this behavior as follows:

 jw.Formatting = Formatting.Indented; jw.WriteStartObject(); ... 

additional literature


So that each entry is added to a new line, you can simply write a new line character after you have written your JSON object, for example:

 ... jw.WriteEndObject(); jw.WriteRaw("\n"); 

Or by calling WriteLine in the underlying TextWriter , although this needs to be done outside of this method.

+11
source

Found out this, although not sure if there is a cleaner way. I added

 jw.WriteWhitespace(Environment.NewLine); 

in the end. Now everything looks good:

{"TimeStamp": "2014-03-10T15: 04: 27,0128185", ...}
{"TimeStamp": "2014-03-10T15: 04: 27,0128185", ...}
...

+1
source

All Articles