我正在序列化一个对象集合,其中包含一个名为动态属性的字典。
发出的默认 Json 如下所示:
[{"dynamicProperties":{"WatchId":7771,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5580"}},
{"dynamicProperties":{"WatchId":7769,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5574"}},
{"dynamicProperties":{"WatchId":7767,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5572"}},
{"dynamicProperties":{"WatchId":7765,"Issues":0,"WatchType":"y","Location":"Equinix Source","Name":"highlight_SM"}},
{"dynamicProperties":{"WatchId":8432,"Issues":0,"WatchType":"y","Location":"Test Devices","Name":"Cisco1700PI"}}]
我想生成如下所示的 Json:
[{"WatchId":7771,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5580"},
{"WatchId":7769,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5574"},
{"WatchId":7767,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5572"},
{"WatchId":7765,"Issues":0,"WatchType":"y","Location":"Equinix Source","Name":"highlight_SM"},
{"WatchId":8432,"Issues":0,"WatchType":"y","Location":"Test Devices","Name":"Cisco1700PI"}]
从阅读 Json.Net 文档看来,我可以为我的班级构建一个 CustomContractResolver,但我找不到有关如何进行此操作的任何详细信息……任何人都可以阐明我应该研究的方向吗?
我要序列化的类如下。
我需要一个允许动态样式行为并且还可以通过 WCF 序列化和反序列化的类。
[DataContract]
public class SerializableDynamicObject : IDynamicMetaObjectProvider
{
[DataMember]
private IDictionary<string, object> dynamicProperties = new Dictionary<string, object>();
#region IDynamicMetaObjectProvider implementation
public DynamicMetaObject GetMetaObject(Expression expression)
{
return new SerializableDynamicMetaObject(expression,
BindingRestrictions.GetInstanceRestriction(expression, this), this);
}
#endregion
#region Helper methods for dynamic meta object support
internal object setValue(string name, object value)
{
dynamicProperties.Add(name, value);
return value;
}
internal object getValue(string name)
{
object value;
if (!dynamicProperties.TryGetValue(name, out value))
{
value = null;
}
return value;
}
internal IEnumerable<string> getDynamicMemberNames()
{
return dynamicProperties.Keys;
}
#endregion
}