Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert booleans in the decoded json-file into lower case strings?

The class I'm decoding to uses string fields and the Newtonsoft default decoder converts the booleans in the json-file into uppercase strings. It probably invokes the ToString() of the Boolean type which results in either "True" or "False".

void Main()
{
    var foo = JsonConvert.DeserializeObject<Foo>("{Prop:true}");
    Console.WriteLine(foo.Prop); // output: True, desired output: true
}

public class Foo
{
    public string Prop{get;set;}
}

Since the field can be either string or boolean in the json, I like to have a custom decoder that always converts json-booleans to "true" or "false" depending on the value.

Any help would be appreciated.

like image 919
Patrik Meijer Avatar asked Nov 02 '22 12:11

Patrik Meijer


1 Answers

How about something like this:

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        string str = token.Value<string>();
        if (string.Equals("true", str, StringComparison.OrdinalIgnoreCase) ||
            string.Equals("false", str, StringComparison.OrdinalIgnoreCase))
        {
            str = str.ToLower();
        }
        return str;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Demo:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        { 
            ""Bool1"": true, 
            ""Bool2"": ""TRUE"", 
            ""Bool3"": false, 
            ""Bool4"": ""FALSE"",
            ""Other"": ""Say It Isn't True!"" 
        }";

        Foo foo = JsonConvert.DeserializeObject<Foo>(json, new BoolStringConverter());

        Console.WriteLine("Bool1: " + foo.Bool1);
        Console.WriteLine("Bool2: " + foo.Bool2);
        Console.WriteLine("Bool3: " + foo.Bool3);
        Console.WriteLine("Bool4: " + foo.Bool4);
        Console.WriteLine("Other: " + foo.Other);
    }
}

class Foo
{
    public string Bool1 { get; set; }
    public string Bool2 { get; set; }
    public string Bool3 { get; set; }
    public string Bool4 { get; set; }
    public string Other { get; set; }
}

Output:

Bool1: true
Bool2: true
Bool3: false
Bool4: false
Other: Say It Isn't True!
like image 154
Brian Rogers Avatar answered Nov 14 '22 07:11

Brian Rogers