我有一个用于 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
public class Outer {
public int Id { get; set; }
[JsonConverter(typeof(InterfaceLabelConverter))]
public Guid? ProductFamilyId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何在WriteJson方法中访问当前属性的名称?我想用另一个属性名将旧值写入 writer,如下所示:
{ Id: 1234, ProductFamilyId: 'newValue', ProductFamilyIdOld: 'oldValue' }
Run Code Online (Sandbox Code Playgroud)
我建议简单地将转换后的 GUID 设为包含类上的私有仅获取属性。如果你标记它,[JsonProperty]它将被序列化:
public class Outer
{
public int Id { get; set; }
public Guid? ProductFamilyId { get; set; }
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
Guid? OldProductFamilyId
{
get
{
return Convert(ProductFamilyId);
}
}
private Guid? Convert(Guid? guid)
{
if (guid != null)
{
var bytes = guid.Value.ToByteArray();
bytes[0] = unchecked((byte)~bytes[0]); // For example
guid = new Guid(bytes);
}
return guid;
}
}
Run Code Online (Sandbox Code Playgroud)
话虽这么说,您可以从属性中选择当前的属性名称JsonWriter.Path:
public class InterfaceLabelConverter : JsonConverter
{
private Guid? Convert(Guid? guid)
{
if (guid != null)
{
var bytes = guid.Value.ToByteArray();
bytes[0] = unchecked((byte)~bytes[0]); // For example
guid = new Guid(bytes);
}
return guid;
}
public override bool CanConvert(Type objectType)
{
throw new InvalidOperationException(); // This converter should only be applied directly to a property.
}
public override bool CanRead { get { return false; } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var path = writer.Path;
var propertyName = path.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Last(); // Throw an exception if not found.
if (propertyName.StartsWith("[") && propertyName.EndsWith("]"))
throw new InvalidOperationException(); // Trying to use this converter for an array element.
var guid = (Guid?)value;
writer.WriteValue(guid);
if (guid != null)
{
// Note -- actually the converter isn't called for null values, see
// /sf/ask/618377301/
var nextGuid = Convert(guid);
var nextName = "Old" + propertyName;
writer.WritePropertyName(nextName);
writer.WriteValue(nextGuid);
}
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
public class Outer
{
public int Id { get; set; }
[JsonConverter(typeof(InterfaceLabelConverter))]
public Guid? ProductFamilyId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13510 次 |
| 最近记录: |