0

I would like to force Newtonsoft.Json's JsonConvert.SerializeObject to always threat bool values as strings: "true" and "false".

I know that JsonConvert is a static class, and I should probably write an extension method something like this one:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {}

but to be honest I have no idea how to do it nor how to implement it into my method:

public static string Serialize(Foo fooData)
{
    return JsonConvert.SerializeObject(fooData);
}

I would appreciate any suggestions.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • 1
    This quite similar question could help: https://stackoverflow.com/questions/9738324/jsonnet-boolean-serialization – Flat Eric Mar 12 '19 at 15:48

1 Answers1

6

You can make a simple JsonConverter to do this:

public class BoolToStringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(bool);
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue((bool)value ? "true" : "false");
    }
}

Then use it like this:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new BoolToStringConverter() },
    Formatting = Formatting.Indented
};

var json = JsonConvert.SerializeObject(obj, settings);

Demo: https://dotnetfiddle.net/aEO1hG

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300