I am trying to serialize a nullable struct using JSON.NET with a custom JsonConverter
. I would like a null
value to be ignored/omitted in the JSON output e.g. I want my JSON output below to be {}
instead of {"Number":null}
. How can this be achieved? Here is a minimal repro with a unit test with what I'm trying to achieve.
[Fact]
public void UnitTest()
{
int? number = null;
var json = JsonConvert.SerializeObject(
new Entity { Number = new HasValue<int?>(number) },
new JsonSerializerSettings()
{
DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
});
Assert.Equal("{}", json); // Fails because json = {"Number":null}
}
public class Entity
{
[JsonConverter(typeof(NullJsonConverter))]
public HasValue<int?>? Number { get; set; }
}
public struct HasValue<T>
{
public HasValue(T value) => this.Value = value;
public object Value { get; set; }
}
public class NullJsonConverter : JsonConverter
{
public override bool CanRead => false;
public override bool CanConvert(Type objectType) => true;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => throw new NotImplementedException();
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var values = (HasValue<int?>)value;
var objectValue = values.Value;
if (objectValue == null)
{
// How can I skip writing this property?
}
else
{
var token = JToken.FromObject(objectValue, serializer);
token.WriteTo(writer);
}
}
}