您可以为StringId 添加TypeConverter。 Json.NET 将获取类型转换器并使用它来将其从字符串转换为字符串:
[TypeConverter(typeof(StringIdConverter))]
class StringId
{
public string Value { get; set; }
}
class StringIdConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(StringId))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
return new StringId { Value = (string)value };
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is StringId)
{
return ((StringId)value).Value;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
如果您的字符串表示包含嵌入的数字或日期/时间数据,请务必使用传入的 culture 而不是默认的当前文化转换该数据。 Json.NET 将使用正确的文化 which is the invariant culture by default 调用转换器,从而确保生成的 JSON 文件可在文化之间移植。
示例fiddle。
但是请注意,如果您使用的是 .Net Core,则仅在 Json.NET 10.0.1 之后才添加了对类型转换器的支持。自 10.0.3 起,Json.NET Portable 版本不支持类型转换器。
或者,如果您不介意将 Json.NET 特定属性添加到您的类型,您可以使用 custom JsonConverter:
[JsonConverter(typeof(StringIdConverter))]
class StringId
{
public string Value { get; set; }
}
class StringIdConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(StringId);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var token = JToken.Load(reader);
return new StringId { Value = (string)token };
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var id = (StringId)value;
writer.WriteValue(id.Value);
}
}
您也可以在global settings中设置转换器。
示例fiddle。