使用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的想法的变体。 将字符串属性设为私有,并将转换逻辑放在那里。 由于[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
你能使用不同的属性来返回字符串的 int 部分吗?
public class Tags
{
[JsonProperty("tiger:maxspeed")]
public string Maxspeed { get; set; }
[JsonIgnore]
public int MaxSpeedInt => int.Parse(Maxspeed.Split(' ')[0]);
}