c# - 如何让 newtonsoft 将 yes 和 no 反序列化为 bool 值

标签 c# class serialization extend json.net

注意:我已在此提要底部提供了解决方案。

我有一个 C# Win 8 应用程序,我正在反序列化一些如下所示的 json:

{
    'Unit': [
        {
            'name':'House 123',
            isAvailable:'no'
        },
        {
            'name':'House 456',
            isAvailable:'yes'
        }]
}

进入一个使用这个接口(interface)的类:

public interface IUnit
{
    string Name { get; }
    bool isAvailable { get; }
}

但是 Newtonsoft 抛出一个错误:

Unexpected character encountered while parsing value: n. Path 'Unit[0].isAvailable, line 1, position 42.

有没有办法扩展 Newtonsoft 以根据结果对象属性类型 bool 解析是/否或 1/0?现在它只适用于 true/false。

有几篇关于类的自定义转换器的帖子,但没有像 bool 这样的原始类型。

有什么建议吗?

最佳答案

public class MyBooleanConverter : JsonConverter
{
    public override bool CanWrite { get { return false; } }

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var value = reader.Value;

        if (value == null || String.IsNullOrWhiteSpace(value.ToString()))
        {
            return false;
        }

        if ("yes".Equals(value, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        return false;
    }

    public override bool CanConvert(Type objectType)
    {
        if (objectType == typeof(String) || objectType == typeof(Boolean))
        {
            return true;
        }
        return false;
    }
}


public interface IUnit
{
    string Name { get; }

    [JsonConverter(typeof(MyBooleanConverter))]
    bool isAvailable { get; }
}

关于c# - 如何让 newtonsoft 将 yes 和 no 反序列化为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14524669/

相关文章:

serialization - GWT 序列化问题

c# - 控制台应用程序未关闭

C#程序导致蓝屏?

c# - 在 C# 桌面应用程序中播放视频

java - 如何在 Java 中使用单独的枚举类引用静态类?

ruby-on-rails - 事件模型序列化程序嵌套关联无问题

c# - 在 C# 中使用枚举值反序列化 Dictionary<string, object>

c# - 使用 MVVM 从列表拖放到 Windows Phone 上的 Canvas

c# - C# 中值相等的自定义类的最健壮的 Equals 实现

java - 在我的 Activity 类中使用构造函数有意义吗?