intercept JSON in C# to return a list of nullable boolean pt. 2

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
					
public class Program
{
	public static void Main()
	{
		string json = @"{
              ""exemptBenefits"": [
                 ""1"",
                 ""0"",
                 ""true"",
                 ""false"",
                 ""yes"",
                 ""no"",
                 ""YES"",
                 ""something else"",
                 ""TRUE"",
                 null
              ],
              ""_apiEndpoint"": ""/benefits/loan""
            }";
		
		var loan = JsonConvert.DeserializeObject<Loan>(json);
		Console.WriteLine(string.Join("\r\n", loan.ExemptBenefits.Select(b => b.HasValue ? b.Value.ToString() : "null")));
	}
}

class Loan
{
    [JsonProperty(ItemConverterType = typeof(NullableBoolDeSerializer))]
	public List<bool?> ExemptBenefits { get; set; }
}

class NullableBoolDeSerializer : JsonConverter
{
	readonly string[] TrueStrings = { "true", "yes", "1" };
	
	public override bool CanConvert(Type objectType)
	{
		return objectType == typeof(bool?);
	}
	
	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		string b = (string)reader.Value;
		return b != null ? TrueStrings.Contains(b.ToLower()) : (bool?)null;
	}
	
	public override bool CanWrite
	{
		get { return false; }
	}
	
	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
	{
		throw new NotImplementedException();
	}
}
;