3

If I serialize a bool value I get something like this:

myboolValue: False

I realize that this is due to Microsoft's ToString() implementation of bools.

Is there a setting that I can change in Newtonsoft to output false like:

myboolValue: false

I can switch to string with a conditional ? "true" : "false", but that adds quotes in the JSON like:

myboolValue: "false"

Can a custom serializer remove the quotes?

Llazar
  • 3,167
  • 3
  • 17
  • 24
MVinca
  • 291
  • 2
  • 4
  • 11
  • 10
    Why are you storing booleans as strings to begin with? What's wrong with a `bool`? – Frontear Jan 11 '19 at 18:55
  • Have you looked at implementing a custom converter? [JSonNet boolean serialization](https://stackoverflow.com/questions/9738324/jsonnet-boolean-serialization) – Rufus L Jan 11 '19 at 18:57
  • 3
    @RufusL I don't think a custom converter is needed here, the desired behavior is the default behavior for boolean types in JSON.NET. – Jonathon Chase Jan 11 '19 at 18:59
  • 3
    see https://dotnetfiddle.net/fNLCAP - looks fine to me – Sir Rufo Jan 11 '19 at 19:11
  • @SirRufo Yes, that does look right. Either .NET Core is behaving differently, or we are messing something else up on our end. Frontear: We are using bool, we only switch to string in my 3rd example to try to work around. Looks like I have more investigation to do. Sorry for the bad question. – MVinca Jan 11 '19 at 19:54
  • 2
    @MVinca - Json.NET serializes `bool` as specified by the [JSON standard](https://json.org/) on .Net core as well as .Net full framework. Possibly your framework has a custom `JsonConverter` that is messing things up? Try adding `[JsonConverter(typeof(NoConverter))]` to your Boolean property where `NoConverter` comes from [this answer](https://stackoverflow.com/a/39739105/3744182), it will suppress any global converter. But beyond that I think we need a [mcve]. – dbc Jan 11 '19 at 22:24

1 Answers1

11

Newtonsoft.Json serializes bool as true/false out of the box:

using System;
using Newtonsoft.Json;

public class Test
{
    public bool f1;
    public bool f2;

    public Test()
    {
        f1 = false;
        f2 = true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var json = JsonConvert.SerializeObject(new Test());
        Console.WriteLine(json);
    }
}

Outputs to console:

{"f1":false,"f2":true}

Additionally you can use improved JSON bool converter which writes C# bool as true/false and able to read bool from true/false/yes/no/1/0 string values of any upper/lower case:

/// <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>
    /// 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 )
    {
        writer.WriteValue((bool)value);
    }

    #endregion Overrides of JsonConverter
}

To register this converter use the code:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    Converters = new List<JsonConverter>
    {
        new BooleanJsonConverter()
    }
}; 
chronoxor
  • 3,159
  • 3
  • 20
  • 31