我有一个(简化的)对象,像这样:
public class Contact
{
[Ignore]
public string Name { get; set;}
}
然后我对对象进行序列化和反序列化,以创建深度复制克隆(https://stackoverflow.com/a/78612/2987066),如下所示:
var deserializeSettings = new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace,
};
var clone = JsonConvert.SerializeObject(contact, deserializeSettings);
return JsonConvert.DeserializeObject<T>(clone);
但该属性不会被复制
是否可以序列化标记为[Ignore]
的属性。也许使用JsonSerializerSettings
还是我需要将其标记为[JSONProperty]
答案 0 :(得分:1)
我想做到这一点的一种方法是重新添加被忽略的字段:
JsonConvert.DeserializeObject<Contact>(clone).Name=contact.Name
但是使用ignore的目的是使它不会被序列化。
另一个选择是在jsonserializersettings中指定自定义合同解析器:
var deserializeSettings = new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace,
ContractResolver = new DynamicContractResolver()
};
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_IContractResolver.htm
public class DynamicContractResolver: DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
//property.HasMemberAttribute = true;
property.Ignored = false;
//property.ShouldSerialize = instance =>
//{
// return true;
//};
return property;
}
}