1

I have a (simplified) object like so:

public class Contact 
{
    [Ignore]
    public string Name { get; set;}
}

and I serialize and deserialise the object to create a deep copy clone (https://stackoverflow.com/a/78612/2987066) like so:

var deserializeSettings = new JsonSerializerSettings 
{
    ObjectCreationHandling = ObjectCreationHandling.Replace,
};

var clone = JsonConvert.SerializeObject(contact, deserializeSettings);

return JsonConvert.DeserializeObject<T>(clone);

but the property does not get copied across

Is it possible to serialise properties marked as [Ignore]. Maybe using JsonSerializerSettings or do I need to mark it as [JSONProperty]

JKennedy
  • 18,150
  • 17
  • 114
  • 198

1 Answers1

1

I guess one way to do this is add the ignored fields back:

JsonConvert.DeserializeObject<Contact>(clone).Name=contact.Name

But the point of using ignore is so that it doesn't get serialized.

Another option is to specify a custom contract resolver in 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;
    }
}
terrencep
  • 675
  • 5
  • 16