【问题标题】:Parse JSON property during deserialization在反序列化期间解析 JSON 属性
【发布时间】:2019-05-30 18:24:32
【问题描述】:

使用 JSON 的以下部分:

"tags": 
{
  "tiger:maxspeed": "65 mph"
}

我有相应的 C# 类用于反序列化:

public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public string Maxspeed { get; set; }

}

我想将其反序列化为整数属性:

public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed { get; set; }

}

是否可以在反序列化过程中将字符串的数字部分从 JSON 解析为 int

我想我想要这样的东西:

public class Tags
{
    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed 
    {
        get
        {
            return _maxspeed;
        }
        set
        {
            _maxspeed = Maxspeed.Parse(<incoming string>.split(" ")[0]);
        }
    }
}

【问题讨论】:

  • @dbc 我更正了不一致的属性名称。我的问题重申:由于“65 mph”本质上是一个字符串,我想知道是否有办法在空白处拆分传入的字符串并在反序列化期间转换为int

标签: c# json.net


【解决方案1】:

我会建议@djv 的想法的变体。将字符串属性设为私有并将转换逻辑放在那里。由于[JsonProperty] 属性,序列化程序会选择它,但它不会混淆类的公共接口。

public class Tags
{
    [JsonIgnore]
    public int MaxSpeed { get; set; }

    [JsonProperty("tiger:maxspeed")]
    private string MaxSpeedString
    {
        get { return MaxSpeed + " mph"; }
        set 
        {
            if (value != null && int.TryParse(value.Split(' ')[0], out int speed))
                MaxSpeed = speed;
            else
                MaxSpeed = 0;
        }
    }
}

小提琴:https://dotnetfiddle.net/SR9xJ9

或者,您可以使用自定义 JsonConverter 将转换逻辑与模型类分开:

public class Tags
{
    [JsonProperty("tiger:maxspeed")]
    [JsonConverter(typeof(MaxSpeedConverter))]
    public int MaxSpeed { get; set; }
}

class MaxSpeedConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // CanConvert is not called when the converter is used with a [JsonConverter] attribute
        return false;   
    }

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

        int speed;
        if (val != null && int.TryParse(val.Split(' ')[0], out speed))
            return speed;

        return 0;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue((int)value + " mph");
    }
}

小提琴:https://dotnetfiddle.net/giCDZW

【讨论】:

    【解决方案2】:

    你可以只使用不同的属性来返回字符串的 int 部分吗?

    public class Tags
    {
    
        [JsonProperty("tiger:maxspeed")]
        public string Maxspeed { get; set; }
    
        [JsonIgnore]
        public int MaxSpeedInt => int.Parse(Maxspeed.Split(' ')[0]);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 2013-08-17
      • 2012-12-09
      • 1970-01-01
      相关资源
      最近更新 更多