将json属性反序列化为bool或double [英] Deserialize json property as bool or double

查看:466
本文介绍了将json属性反序列化为bool或double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json:

"rates": {
        "AT": {
            "country": "Austria",
            "standard_rate": 20.00,
            "reduced_rate": 10.00,
            "reduced_rate_alt": 13.00,
            "super_reduced_rate": false,
            "parking_rate": 12.00
        },
        "DK": {
            "country": "Denmark",
            "standard_rate": 25.00,
            "reduced_rate": false,
            "reduced_rate_alt": false,
            "super_reduced_rate": false,
            "parking_rate": false
        },
}

我有下面的类可反序列化json:

And I have the following class to deserialize the json:

    public string country { get; set; }
    public double standard_rate { get; set; }
    //public string reduced_rate { get; set; }
    private double _reduced_rate;

    public double reduced_rate
    {
        get { return _reduced_rate; }
        set
        {
            bool isDouble = Double.TryParse(value.ToString(), out _reduced_rate);
            if (isDouble)
                _reduced_rate = value;
            else
                _reduced_rate = 0.0;
        }
    }

    public string reduced_rate_alt { get; set; }
    public string super_reduced_rate { get; set; }
    public string parking_rate { get; set; }

reduce_rate的值是false时,我要设置0.0,否则要设置double值.但是在set方法中,切勿进入else.

And when the value of reduce_rate is a false I want to set a 0.0 else the double value. But in the set method never enters into the else.

还有另一种方法可以解决这种情况吗?

Is there another approach to resolve this situation?

推荐答案

一种解决方法是将reduced_rate_alt定义为字符串,然后定义一个新属性,该属性读取并尝试将其解析为吸气剂.那可以工作,但是您有几个类似的工作,并且由于使用JSON.NET,同一转换器应该对所有这些工作,因此我将手动转换这些属性:

One way to handle this would be to define reduced_rate_alt as a string and then define a new property which reads and tries to parse that to a value in the getter. That can work but you have several like that and since using JSON.NET, the same converter should work with all of them, I'd manually convert those properties:

[JsonConverter(typeof(RateJsonConverter))]
public decimal reduced_rate_alt { get; set; }

修饰每个属性,该属性可能会返回false.这告诉JSON.NET您正在提供用于反序列化此属性的代码.在使用它时,您可能还想用[JsonProperty]修正属性名称.

Adorn each of the properties which might return false with that attribute. This tells JSON.NET that you are supplying the code to deserialize this property. While you are at it you may want to also fix up the property names with [JsonProperty].

规则/转换实现只是将false使用0,否则使用值.只要它们的转换规则都相同,就可以对每个属性使用相同的转换器.我也将类型更改为十进制,这可能更适合于这些.

The rule/conversion implements is simply to use 0 for false otherwise the value. As long as the conversion rule is the same for all of them, you can use the same converter for each property. I also changed the type to decimal which is probably more appropriate for these.

public class RateJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {   // name used in a previous answer
        return (objectType == typeof(VRate));
    }

    public override object ReadJson(JsonReader reader, Type objectType, 
                                object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        decimal d = 0M;

        Decimal.TryParse(token.ToString(), out d);        
        return d;
    }

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

测试:

var rates = JsonConvert.DeserializeObject<VRates>(jstr).rates;

foreach (KeyValuePair<string, VRate> kvp in rates)
{
    Console.WriteLine("key: {0} ({1}), reduced alt rate: {2}", kvp.Key, 
        kvp.Value.country,
        kvp.Value.reduced_rate_alt.ToString("F2"));
    kvp.Value.VTag = kvp.Key;
}

前几个输出:

键:AT(奥地利),降低的转换率:13.00
键:BE(比利时),降低的转换率:6.00
钥匙:BG(保加利亚),降低的转换率:0.00
键:CY(塞浦路斯),降低的转换率:5.00
钥匙:捷克(捷克共和国),降低的转换率:10.00
键:DK(丹麦),降低的更改率:0.00

key: AT (Austria), reduced alt rate: 13.00
key: BE (Belgium), reduced alt rate: 6.00
key: BG (Bulgaria), reduced alt rate: 0.00
key: CY (Cyprus), reduced alt rate: 5.00
key: CZ (Czech Republic), reduced alt rate: 10.00
key: DK (Denmark), reduced alt rate: 0.00

BG和DK为假并转换为0,而其他的则具有JSON中列出的速率.

BG and DK are false and convert to 0, while the others have the rate listed in the JSON.

这篇关于将json属性反序列化为bool或double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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