一种可能性是创建一个自定义ContractResolver
,当序列化特定类型的对象时TTarget
,添加一个合成器,该合成ExtensionDataGetter
器为指定的目标返回IEnumerable<KeyValuePair<Object, Object>>
其对应的DynamicPropertyManager<TTarget>
.
首先,定义合约解析器如下:
public class DynamicPropertyContractResolver<TTarget> : DefaultContractResolver
{
readonly DynamicPropertyManager<TTarget> manager;
readonly TTarget target;
public DynamicPropertyContractResolver(DynamicPropertyManager<TTarget> manager, TTarget target)
{
if (manager == null)
throw new ArgumentNullException();
this.manager = manager;
this.target = target;
}
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
if (objectType == typeof(TTarget))
{
if (contract.ExtensionDataGetter != null || contract.ExtensionDataSetter != null)
throw new JsonSerializationException(string.Format("Type {0} already has extension data.", typeof(TTarget)));
contract.ExtensionDataGetter = (o) =>
{
if (o == (object)target)
{
return manager.Properties.Select(p => new KeyValuePair<object, object>(p.Name, p.GetValue(o)));
}
return null;
};
contract.ExtensionDataSetter = (o, key, value) =>
{
if (o == (object)target)
{
var property = manager.Properties.Where(p => string.Equals(p.Name, key, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
if (property != null)
{
if (value == null || value.GetType() == property.PropertyType)
property.SetValue(o, value);
else
{
var serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { ContractResolver = this });
property.SetValue(o, JToken.FromObject(value, serializer).ToObject(property.PropertyType, serializer));
}
}
}
};
contract.ExtensionDataValueType = typeof(object);
}
return contract;
}
}
然后按如下方式序列化您的对象:
var obj = new object();
//Add prop to instance
int propVal = 0;
var propManager = new DynamicPropertyManager<object>(obj);
propManager.Properties.Add(
DynamicPropertyManager<object>.CreateProperty<object, int>(
"Value", t => propVal, (t, y) => propVal = y, null));
propVal = 3;
var settings = new JsonSerializerSettings
{
ContractResolver = new DynamicPropertyContractResolver<object>(propManager, obj),
};
//Serialize object here
var json = JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
Console.WriteLine(json);
哪些输出,根据需要,
{"Value":3}
显然,这可以通过将动态属性管理器和目标的集合传递给增强的DynamicPropertyContractResolver<TTarget>
. 只要合约解析器具有从被(反)序列化的目标映射到ExtensionDataGetter
其.ExtensionDataSetter
DynamicPropertyManager
限制:如果TTarget
类型已经有扩展数据成员,这将不起作用。