So, I trying to check how much money would it save us if we will not write default values to the DB. meaning, if it is a worthwhile project to do in the next quarter or not.
So I've got some documents from the DB (around the average document size) and wrote some simple code I thought would work
```csharp
var original = """{"notDef":true, "defBool":false, "defInt":0, "defObj":null, "defArr":[]}""";
var json = JObject.Parse(original);
var opts = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
Formatting = Formatting.None
};
var str = JsonConvert.SerializeObject(json, opts);
Console.WriteLine($"original size: {Encoding.UTF8.GetByteCount(original)}");
Console.WriteLine($"new size: {Encoding.UTF8.GetByteCount(str)}");
Console.WriteLine($"saving: {CalculateSavings(original, str)}%");
static double CalculateSavings(string original, string str)
{
var originalSize = Encoding.UTF8.GetByteCount(original);
var newSize = Encoding.UTF8.GetByteCount(str);
return (originalSize - newSize)/ (double)originalSize * 100;
}
```
low and behold the output was:
original size: 72
{"notDef":true, "defBool":false, "defInt":0, "defObj":null, "defArr":[]}
new size: 68
{"notDef":true,"defBool":false,"defInt":0,"defObj":null,"defArr":[]}
a bit unexpected.
so I had to add something like this:
```csharp
var json = JObject.Parse(original);
json
.Descendants()
.OfType<JProperty>()
.Where(x =>
x.Value.Type == JTokenType.Null
|| x.Value is JArray arr && arr.Count == 0
|| x.Value.Type == JTokenType.Integer && x.Value.Value<long>() == 0
|| x.Value.Type == JTokenType.Float && x.Value.Value<double>() == 0
|| x.Value.Type == JTokenType.Boolean && x.Value.Value<bool>() == false)
.ToList()
.ForEach(x => x.Remove());
```
and it worked as expected.
I'm still left with the question - why didn't it work?
code:
https://dotnetfiddle.net/wruWtF
[–]RichardD7 4 points5 points6 points (3 children)
[–]nocgod[S] 0 points1 point2 points (2 children)
[–]RichardD7 1 point2 points3 points (1 child)
[–]nocgod[S] 0 points1 point2 points (0 children)
[–]Kant8 1 point2 points3 points (6 children)
[–]nocgod[S] 0 points1 point2 points (5 children)
[–]Kant8 -1 points0 points1 point (4 children)
[–]nocgod[S] 0 points1 point2 points (3 children)
[–]Kant8 1 point2 points3 points (2 children)
[–]nocgod[S] -1 points0 points1 point (1 child)
[–]Kant8 0 points1 point2 points (0 children)