如何自定义Json.NET以序列化私有成员而不是序列化公共只读属性(不使用属性)。
我已经开始创建自定义IContractResolver
,但有点迷失。
答案 0 :(得分:9)
对于部分答案,弄乱DefaultContractResolver.DefaultMembersSearchFlags可以让它包含私人内容:
Newtonsoft.Json.JsonSerializerSettings jss = new Newtonsoft.Json.JsonSerializerSettings();
if (includePrivateMembers)
{
Newtonsoft.Json.Serialization.DefaultContractResolver dcr = new Newtonsoft.Json.Serialization.DefaultContractResolver();
dcr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;
jss.ContractResolver = dcr;
}
return Newtonsoft.Json.JsonConvert.SerializeObject(o, jss);
似乎可以处理很多对象,但有些对象似乎会产生CLR异常。
答案 1 :(得分:3)
回复Chris' answer,DefaultMemberSearchFlags
was deprecated as of version 6上的DefaultContractResolver
属性。尽管弃用消息的内容如此,但我相信您也需要覆盖CreateProperties
方法,例如L.B explains。
此方法可让您完全控制,包括排除只读属性:
class PrivateContractResolver : DefaultContractResolver
{
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
MemberInfo[] fields = objectType.GetFields(flags);
return fields
.Concat(objectType.GetProperties(flags).Where(propInfo => propInfo.CanWrite))
.ToList();
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return base.CreateProperties(type, MemberSerialization.Fields);
}
}