假设我有一个类型,其值可以用整数完全表示但具有验证逻辑,并且它将在Web API中返回并被接受。为了保持良好的代码并避免原始的痴迷,我可能会做类似的事情:
public class FiscalPeriod
{
public FiscalPeriod(int id)
{
if (!Validator.IsValidPeriod(id))
throw new ArgumentException($"Invalid fiscal period ID '{id}'", nameof(id));
Id = id;
}
public int Id { get; private set; }
public override string ToString() => Id.ToString();
public static implicit operator int(FiscalPeriod period) => period.Id;
}
然后,当Web API调用返回此类型时,它将被序列化为JSON:
"FiscalPeriod" : {"Id": 201601},
是否有办法强迫它序列化为以下内容?
"FiscalPeriod" : 201601,
这样可以更容易地在客户端处理为普通数字?
答案 0 :(得分:4)
You can tell Json.Net how to deal with the type using the JsonConverter attribute.
public class ViewModel
{
public FiscalPeriod FiscalPeriod { get; set; }
}
public class FiscalPeriodConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var fiscalPeriod = value as FiscalPeriod;
writer.WriteStartObject();
serializer.Serialize(writer, fiscalPeriod.Id);
writer.WriteEndObject();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return typeof(FiscalPeriod).IsAssignableFrom(objectType);
}
}
[JsonConverter(typeof(FiscalPeriodConverter))]
public class FiscalPeriod
{
public FiscalPeriod(int id)
{
if (!Validator.IsValidPeriod(id))
throw new ArgumentException($"Invalid fiscal period ID '{id}'", nameof(id));
Id = id;
}
public int Id { get; private set; }
public override string ToString() => Id.ToString();
public static implicit operator int(FiscalPeriod period) => period.Id;
}
http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverterAttribute.htm