5

我正在解码的类使用字符串字段,Newtonsoft 默认解码器将 json 文件中的布尔值转换为大写字符串。它可能会调用 Boolean 类型的 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”。

任何帮助,将不胜感激。

4

2 回答 2

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!
于 2013-10-18T00:47:22.023 回答
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();
    }
}
于 2016-10-18T08:52:42.983 回答