Organic Platypus
Organic Platypus

Reputation: 71

Make Json.Net serialize booleans as strings

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.

Upvotes: 1

Views: 2702

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129777

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

Upvotes: 7

Related Questions