Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.net JsonIgnoreAttribute not working with "EntityKey" property

I am using JSON.net to serialize my EntityFramework objects.

In the past, I have created a class that applies the "JsonIgnore" attribute to a property, and then I set the "MetadataType" attribute of my main EntityFramework class to that newly created class.

Here is an example:

The class that will be applied to the EF class:

 public class Role_DoNotSerialize
    {
        [JsonIgnore]
        public string Users { get; set; }
    }

The partial class file for the EF class:

[MetadataType(typeof(Role_DoNotSerialize))]
    public partial class Role
    { 
    }

In the above example, the property "Users" will not be serialized when serializing a "Role" object.

My problem is, this same technique fails to work when I add in the EntityKey property like so:

public class Role_DoNotSerialize
    {
        [JsonIgnore]
        public string Users { get; set; }

        [JsonIgnore]
        public System.Data.EntityKey EntityKey { get; set; }
    }

Using this class, the "EntityKey" property is still serialized. What am I doing wrong?

like image 732
Amanda Kitson Avatar asked Dec 21 '11 14:12

Amanda Kitson


1 Answers

you can do this by implementing your own ContractResolver ( example code with JSON.NET 4.5, but also possible with older versions )

public class ExcludeEntityKeyContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> properties = base.CreateProperties(type,memberSerialization);
        return properties.Where(p => p.PropertyType != typeof (System.Data.EntityKey)).ToList();
    }
}

you can then set this to set the ContractResolver for your JsonSerializerSettings object

JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new ExcludeEntityKeyContractResolver();

Note that you are not limited to just that one lambda function but that you can implement any sort of checks you want. You can even override the Converter per property to do custom serialization.

like image 164
Willem D'Haeseleer Avatar answered Sep 19 '22 12:09

Willem D'Haeseleer