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

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
					
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
{
	[JsonConverter(typeof(NullableBoolListDeSerializer))]
	public List<bool?> ExemptBenefits { get; set; }
}

class NullableBoolListDeSerializer : JsonConverter
{
	readonly string[] TrueStrings = { "true", "yes", "1" };
	
	public override bool CanConvert(Type objectType)
	{
		return objectType == typeof(List<bool?>);
	}
	
	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		return JArray.Load(reader)
			.Children<JValue>()
			.Select(jv =>
					{
						string b = (string)jv;
						return b != null ? TrueStrings.Contains(b, StringComparer.OrdinalIgnoreCase) : (bool?)null;
					})
			.ToList();
	}
	
	public override bool CanWrite
	{
		get { return false; }
	}
	
	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
	{
		throw new NotImplementedException();
	}
}
;