使用 Json.Net 将 int 转换为 bool [英] Convert an int to bool with Json.Net

查看:53
本文介绍了使用 Json.Net 将 int 转换为 bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用网络服务,返回的 bool 字段数据为 0 或 1,但是对于我的模型,我使用的是 System.Bool

I am calling a webservice and the returned data for a bool field is either 0 or 1 however with my model I am using a System.Bool

使用 Json.Net 是否可以将 0/1 转换为我的模型的布尔值?

With Json.Net is it possible to cast the 0/1 into a bool for my model?

目前我收到一个错误

Newtonsoft.Json.JsonSerializationException:将值0"转换为类型System.Boolean"时出错

Newtonsoft.Json.JsonSerializationException: Error converting value "0" to type 'System.Boolean'

任何帮助都会很棒!!

推荐答案

最终创建了一个转换器

 public class BoolConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((bool)value) ? 1 : 0);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value.ToString() == "1";
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(bool);
    }
}

然后在我的模型中

 [JsonConverter(typeof(BoolConverter))]
    public bool active { get; set; }

希望这对其他人有帮助

这篇关于使用 Json.Net 将 int 转换为 bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆