JSON.net JsonIgnoreAttribute not working with EntityKey property

I use JSON.net to serialize EntityFramework objects.

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

Here is an example:

The class to be applied to the EF class:

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

Partial class file for class EF:

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

In the above example, the Users property will not be serialized when the Role object is serialized.

My problem is that the same method does not work when I add the EntityKey property like this:

 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?

+7
source share
2 answers

you can do this by implementing your own ContractResolver (sample 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 set this to set ContractResolver for your JsonSerializerSettings object

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

Please note that you are not limited to only one lambda function, but you can perform any checks. You can even override the converter for each property to perform custom serialization.

+4
source

I think the latest versions of JSON.NET are reading this now. This sample worked for us on the MVC website, but you could use the string however you want.

 public ActionResult ContentJsonFormatted(object obj, Formatting formatting = Formatting.Indented) { string result = JsonConvert.SerializeObject(obj, formatting); return Content(result, "text/plain"); } 
+2
source

All Articles