Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON.NET serialize everything on a single line?

Tags:

json

c#

json.net

I simply want the JSON.net serializer to write out JSON objects (to file), one object per line but instead it just appends everything on the same top line. All of the JSON.net samples seem to imply that what I want is default behavior but I'm not seeing it work that way. Here's 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();
}

Output looks like this: {object}{obj2}...{objN} all on a single line.

But I want:

{obj1}

{obj2}

...

How do I do this?

like image 751
jeking Avatar asked Mar 13 '14 02:03

jeking


People also ask

How does JSON serialization work?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

Is JSON serialized or Deserialized?

JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization.

What is a JSON serialization exception?

The exception thrown when an error occurs during JSON serialization or deserialization.

Does JSON serialize private fields?

All fields, both public and private, are serialized and properties are ignored.


2 Answers

The samples provided are indented for clarity, but the default behavior is to write the resulting JSON string without any unnecessary whitespace. You can override this behavior like this:

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

Further Reading

  • Formatting enum

To ensure that each entry is appended to a new line, you could simply write a new line character after you've written your JSON object, like this:

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

Or by calling WriteLine on the underlying TextWriter, though that would need to be done outside of this method.

like image 99
p.s.w.g Avatar answered Oct 17 '22 20:10

p.s.w.g


Figured it out, though not sure if there's a cleaner way. I added a

jw.WriteWhitespace(Environment.NewLine);

at the end. Now everything looks good:

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

like image 45
jeking Avatar answered Oct 17 '22 21:10

jeking