I am using JsonConverters in Newtonsoft.json. They will be providing me custom WriteJson / ReadJson code that I will use, so I need both the WriteJson / ReadJson to get triggered when a given objectType matches the converter.
One thing I need to do is convert the "null" keyword that shows up in the json to 0.
Below is a much simplified JsonConverter -- that all it does is attempt to change "null" to 0, (and anything else that's not null to 1). Unfortunately I have discovered that the WriteJson function never gets triggered when value == null.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace ConsoleApp1
{
class Program
{
public class TestConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(B);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return existingValue;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
/// This function never gets triggered when value is null
if (value == null)
{
writer.WriteValue(0);
}
else
{
writer.WriteValue(1);
}
}
}
public class B
{
public int C
{
get; set;
}
}
public class A
{
public B B
{
get; set;
} = null;
}
static void Main(string[] args)
{
var c = JsonConvert.SerializeObject(new A(), new JsonSerializerSettings()
{
Converters = new List<JsonConverter> { new TestConverter() }
});
Console.WriteLine(c);
}
}
}
Output:
{"B":null}
Expected Output:
{"B": 0}
Is there some setting or way to convert all output of "null" to "0" ?