【发布时间】:2013-06-05 19:41:12
【问题描述】:
在 Newtonsoft Json.NET 自定义 JsonConverter 的 WriteJson 方法中,我可以从 JsonConverter 中上诉默认对象序列化行为吗?
也就是说,如果没有注册自定义转换器,我可以推迟序列化吗?
详情
给定一个价格等级
public class Price
{
public string CurrencyCode;
public decimal Amount;
}
正常的 Newtonsoft Json.NET 行为是仅在引用为空时将Price 实例序列化为空。此外,我想在Price.Amount 为零时将Price 实例序列化为null。这是我到目前为止所做的工作 (complete source code)
public class PriceConverter : JsonConverter
{
// ...
public override void WriteJson(
JsonWriter writer,
object value,
JsonSerializer serializer)
{
var price = (Price)value;
if (0 == price.Amount) {
writer.WriteNull();
return;
}
// I'd like to replace the rest of this method with an appeal to the
// default serialization behavior.
writer.WriteStartObject();
writer.WritePropertyName("amount");
writer.WriteValue(price.Amount);
writer.WritePropertyName("currencyCode");
writer.WriteValue(price.CurrencyCode);
writer.WriteEndObject();
}
// ...
}
这个实现的最后一部分是脆弱的。例如,如果我要向Price 添加字段,我的序列化将被破坏(而且我不知道编写检测中断的测试的好方法)。
我的序列化程序有许多行为,通过JsonSerializerSettings 在单独的程序集中配置,我需要保留这些行为(例如,驼峰式属性名称)。我不可能在这两者之间添加直接依赖关系。实际上,我使用[JsonConverter(typeof(PriceConverter))] 属性来指定我的自定义转换器应该用于Price。
【问题讨论】:
-
目前转换器无法访问这些设置,并且库的作者似乎没有计划实施此设置。看到这个问题:json.codeplex.com/workitem/23794 您可以尝试在github.com/JamesNK/Newtonsoft.Json/issues 上提交功能请求我认为仅稍微修改序列化的转换器非常普遍,因此它确实是一个有用的功能。
标签: .net json serialization json.net