Nulls cause problems. Usually, they’re not big problems, but if a field might have a value- or none at all- we have to be careful with how we handle it.

Languages like C# have added Nullable types, which wrap around those problems. But sometimes, you need to cross a boundary between systems. When you send the C# data to JSON, how do you want to represent null values?

You might just send nulls. That’s fine and logical. You might just leave out the null keys (technically sending undefined). Also fine and also logical, as long as those sorts of variations are communicated by your schema.

If you’re Jackie’s co-worker, you might decide that they should just be empty strings. This is a bad choice- if a field is an integer, but it doesn’t have a value, it suddenly turns into a string? But hey, you can document this too, and essentially treat the field as a union type. It’s ugly, but workable.

Now, they use the Newtonsoft serializer to build their JSON, which is flexible and extensible, and with a little munging, can be tricked into converting nulls to strings. It’s a little bit of code, but a perfectly manageable thing, if you really want to do this.

Jackie’s co-worker felt that it was too much code.

This is what they did:

string jsonString = JsonConvert.SerializeObject(dataObj);
string jsonStringNoNull = jsonString.Replace("null", @"""""");

Convert to string, then just do a string Replace swapping the string "null" with an empty string. Notice that there are no guards on it, no checks, no logic- anything instances of null are replaced regardless of where they appear. Hope they don’t have any customers with the name Null, or use any of these words in their field names or data.

So far, it hasn’t caused any noticeable errors. So far.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!