c# - 在反序列化期间解析 JSON 属性

标签 c# json.net

使用 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]);
        }
    }
}

最佳答案

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

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;
        }
    }
}

fiddle :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");
    }
}

fiddle :https://dotnetfiddle.net/giCDZW

关于c# - 在反序列化期间解析 JSON 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56383689/

相关文章:

c# - 如何修复 json.net (Newtonsoft.Json) 运行时文件加载异常

c# - 为什么我的接口(interface)的 BaseType 为空?

c# - 读取两个 JSON 文件并将第一个文件中不存在的第二个文件中存在的所有项目提取到一个新对象

c# - 使用随机根名称的 c# 反序列化 json

C# JSON 文件到列表

c# - 如何在 asp.net web api 中返回 json 错误消息?

c# - 如何将带有某些绑定(bind)参数的任意函数传递给另一个函数?

c# - 结束日期应比开始日期晚五天

c# - FormatterServices.GetUninitializedObject(type) UWP/NETCore 等效

javascript - 从隐藏的代码中过滤 TextBox 的 KeyPress 事件上的 GridView