如何将解码后的json文件中的布尔值转换为小写字符串?

时间:2013-10-17 22:06:19

标签: c# json json.net decoding

我正在解码的类使用字符串字段,而Newtonsoft默认解码器将json文件中的布尔值转换为大写字符串。它可能调用布尔类型的ToString(),导致“True”或“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;}
}

由于字段在json中可以是字符串或布尔值,我喜欢有一个自定义解码器,它总是根据值将json-booleans转换为“true”或“false”。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

这样的事情怎么样:

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();
    }
}

演示:

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; }
}

输出:

Bool1: true
Bool2: true
Bool3: false
Bool4: false
Other: Say It Isn't True!

答案 1 :(得分:0)

/// <summary>
/// Implements a <see cref="JsonStringBoolConverter"/> that will handle serialization of Json Boolean values to strings
///  with capital letter.
/// </summary>
/// <summary>
/// Starting from Newtonsoft.Json v9.0.1 default converting logic has been changed
/// Old logic: 
/// json boolean 'true' => .NET string "True"
/// 
/// New logic:
/// json boolean 'true' => .NET string "true"
/// 
/// Details: https://github.com/JamesNK/Newtonsoft.Json/issues/1019
/// </summary>
public sealed class JsonBooleanStringConverter : JsonConverter
{
    /// <summary>
    /// See <see cref="JsonConverter.CanConvert"/>.
    /// </summary>
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }

    /// <summary>
    /// Specifies that this converter will not participate in writting.
    /// </summary>
    public override bool CanWrite
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// See <see cref="JsonConverter.ReadJson"/>. 
    /// </summary>
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        string str = token.Value<string>();

        if (token.Type == JTokenType.Boolean)
        {
            if (string.Equals("true", str, StringComparison.OrdinalIgnoreCase))
            {
                str = "True";
            }
            else if (string.Equals("false", str, StringComparison.OrdinalIgnoreCase))
            {
                str = "False";
            }
        }

        return str;
    }

    /// <summary>
    /// See <see cref="JsonConverter.WriteJson"/>.
    /// </summary>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}