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.
- It starts with call to
WriteStartObject
method ofJsonTextWriter
- Then it creates parameter name via
WritePropertyName
- Depending on whether primitive value or raw string needs to be written
WriteValue
orWriteRaw
methods are used respectfully - Repeat steps 2 and 3 as needed
- Call to
WriteEndObject
to 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.