WriteEndObject of JSON.NET ouptuts NULL literal

JSON.NET is a very popular framework to process JSON data in .NET. We recently upgraded from v4 to v6 and noticed strange thing it started to output null to JSON strings created by JsonTextWriter object.

For example if JSON produced by v4 would look like this:

{"param1":"value1", "param2":"value2",
"someArray":[{"arrParam1": "arrValue1"}, {"arrParam2": "arrValue2"}]}

Same code, using v6, would prodcuce

{"param1":"value1", "param2":"value2",
"someArray":[{"arrParam1": "arrValue1"}, {"arrParam2": "arrValue2"}]null}

that extra “null” makes it invalid and unusable JSON.

The .NET function to create JSON writes it into a StringBuilder and is pretty straighforward.

  1. It starts with call to WriteStartObject method of JsonTextWriter
  2. Then it creates parameter name via WritePropertyName
  3. Depending on whether primitive value or raw string needs to be written WriteValue or WriteRaw methods are used respectfully
  4. Repeat steps 2 and 3 as needed
  5. Call to WriteEndObjectto finish writing.

This worked perfectly well when version 4 of Newtonsoft.Json.dll was used. After upgrading to version 6 last method – “WriteEndObject” began to output “null” to resulting JSON.

The solution is to use WriteRawValue method instead of WriteRaw – it still outputs raw string, but at the end WriteEndObject doesn’t output “null” anymore.

Leave a Reply

Your email address will not be published. Required fields are marked *