C#Json序列化支持字段引用属性,而不是反过来引用



我使用NewtonSoft.Json最新版本,需要对第三方对象进行序列化。我需要序列化字段。这是我使用的JsonSerializerSettings:

JsonSerializerSettings settings_ = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Include,
    DefaultValueHandling = DefaultValueHandling.Include,
    PreserveReferencesHandling = PreserveReferencesHandling.All,
    ObjectCreationHandling = ObjectCreationHandling.Replace,
    ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
    ContractResolver = new DynamicContractResolver(),
};
public class DynamicContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
    {
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
        properties = properties.Where(p => p.PropertyName != "MonitoringInstance" && p.PropertyName != "SessionInstance").ToList();
        var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(f => CreateProperty(f, memberSerialization));
        return properties.Union(fields, new EqualityComparer()).ToList();
    }
}

不幸的是,无论我如何尝试,backing字段都会引用Property。有什么可以逆转的吗?任何见解都值得赞赏。

简单地用DataContractAttribute装饰类和用DataMemberAttribute装饰字段要容易得多。除非您真的想自己实现合约解析器,否则我们一直在使用JSON。

相关内容

  • 没有找到相关文章

最新更新