带有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]);
}
}
}
答案 0 :(得分:3)
您可以使用其他属性来返回字符串的int部分吗?
public class Tags
{
[JsonProperty("tiger:maxspeed")]
public string Maxspeed { get; set; }
[JsonIgnore]
public int MaxSpeedInt => int.Parse(Maxspeed.Split(' ')[0]);
}
答案 1 :(得分:2)
我建议使用@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");
}
}