Skip to content

Instantly share code, notes, and snippets.

@makomweb
Created April 15, 2022 16:04
Show Gist options
  • Save makomweb/7b01f54d0f39ae17507bb307b76326a7 to your computer and use it in GitHub Desktop.
Save makomweb/7b01f54d0f39ae17507bb307b76326a7 to your computer and use it in GitHub Desktop.
Empty string or null to FALSE conversion
using Newtonsoft.Json;
using NUnit.Framework;
using System;
namespace JSON_empty_string_or_null_to_false_conversion
{
public class MyDocument
{
public bool MyFlag { get; set; }
public bool MyOtherFlag { get; set; }
}
public class EmptyStringToFalseConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(bool);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value != null)
{
string value = reader.Value.ToString().ToLower().Trim();
if (value == "")
{
return false;
}
}
return new JsonSerializer().Deserialize(reader, objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException("This class cannot write JSON!");
}
}
public class NullToFalseConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(bool);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = reader.Value;
if (value == null)
{
return false;
}
return new JsonSerializer().Deserialize(reader, objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException("This class cannot write JSON!");
}
}
public class Tests
{
[Test]
public void Deserialize_empty_string_to_false_should_succeed()
{
var json = "{\"MyFlag\":true,\"MyOtherFlag\":\"\"}";
var doc = JsonConvert.DeserializeObject<MyDocument>(json, new EmptyStringToFalseConverter());
Assert.True(doc.MyFlag);
Assert.False(doc.MyOtherFlag);
}
[Test]
public void Deserialize_null_to_false_should_succeed()
{
var json = "{\"MyFlag\":true,\"MyOtherFlag\":null}";
var doc = JsonConvert.DeserializeObject<MyDocument>(json, new NullToFalseConverter());
Assert.True(doc.MyFlag);
Assert.False(doc.MyOtherFlag);
}
[Test]
public void Deserialize_empty_string_and_null_to_false_should_succeed()
{
var json = "{\"MyFlag\":\"\",\"MyOtherFlag\":null}";
var customConverters = new JsonConverter[]
{
new EmptyStringToFalseConverter(),
new NullToFalseConverter()
};
var doc = JsonConvert.DeserializeObject<MyDocument>(json, customConverters);
Assert.False(doc.MyFlag);
Assert.False(doc.MyOtherFlag);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment