【发布时间】:2015-12-16 18:30:31
【问题描述】:
我有这个用于 guid 属性的示例转换器:
public class CustomGuidConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof (Guid?) || objectType == typeof (Guid);
}
public override void WriteJson(JsonWriter writer, object oldValue, JsonSerializer serializer)
{
if (value != null)
{
var newValue = convert(oldValue); // do some conversion
writer.WriteValue(newValue);
}
}
}
像这样使用它:
public class Outer {
public int Id { get; set; }
[JsonConverter(typeof(InterfaceLabelConverter))]
public Guid? ProductFamilyId { get; set; }
}
如何在WriteJson 方法中访问当前属性的名称?
我想用这样的另一个属性名将旧值写入 writer:
{ Id: 1234, ProductFamilyId: 'newValue', ProductFamilyIdOld: 'oldValue' }
【问题讨论】:
-
旧值从何而来?
-
'oldGuid' 是需要序列化的实际值,'newGuid' 是否与您在问题中提到的转换后的值相同?
-
您希望外部对象的 JSON 看起来像什么? IE。如果外部对象是
public class Outer { public int Id { get; set; } public Guid? ProductFamilyId { get; set; } },那么应该生成什么JSON?