Skip to content

Instantly share code, notes, and snippets.

@ykurniawan
Forked from randyburden/BooleanJsonConverter.cs
Created October 15, 2018 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ykurniawan/0f6dc31b195215f2f5c010a326efd7e4 to your computer and use it in GitHub Desktop.
Save ykurniawan/0f6dc31b195215f2f5c010a326efd7e4 to your computer and use it in GitHub Desktop.
A Json.NET JsonConverter that can handle converting the following values into boolean values: true, false, yes, no, y, n, 1, 0.
using System;
using Newtonsoft.Json;
namespace JsonConverters
{
/// <summary>
/// Handles converting JSON string values into a C# boolean data type.
/// </summary>
public class BooleanJsonConverter : JsonConverter
{
#region Overrides of JsonConverter
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert( Type objectType )
{
// Handle only boolean types.
return objectType == typeof( bool );
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>
/// The object value.
/// </returns>
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
{
switch ( reader.Value.ToString().ToLower().Trim() )
{
case "true":
case "yes":
case "y":
case "1":
return true;
case "false":
case "no":
case "n":
case "0":
return false;
}
// If we reach here, we're pretty much going to throw an error so let's let Json.NET throw it's pretty-fied error message.
return new JsonSerializer().Deserialize( reader, objectType );
}
/// <summary>
/// Specifies that this converter will not participate in writing results.
/// </summary>
public override bool CanWrite { get { return false; } }
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param><param name="value">The value.</param><param name="serializer">The calling serializer.</param>
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
{
}
#endregion Overrides of JsonConverter
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment