Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell Json.NET to ignore properties in a 3rd-party object?

Tags:

The Json.NET documentation says you use JsonIgnore to not serialize certain properties in your classes:

public class Account {     public string FullName { get; set; }     public string EmailAddress { get; set; }      [JsonIgnore]     public string PasswordHash { get; set; } } 

How can I make Json.NET ignore specific properties when serializing a 3rd-party object with JsonConvert.SerializeObject?

like image 607
Thomas Johnson Avatar asked Sep 09 '14 16:09

Thomas Johnson


2 Answers

Make a custom contract resolver:

public class ShouldSerializeContractResolver : DefaultContractResolver {     public static ShouldSerializeContractResolver Instance { get; } = new ShouldSerializeContractResolver();      protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)     {         JsonProperty property = base.CreateProperty(member, memberSerialization);                 if (typeof(Account).IsAssignableFrom(member.DeclaringType) && member.Name == nameof(Account.PasswordHash))         {             property.Ignored = true;         }         return property;     } } 

How I test it:

        var account = new Account         {             PasswordHash = "XXAABB"         };         var settings = new JsonSerializerSettings         {             ContractResolver = ShouldSerializeContractResolver.Instance         };         var json = JsonConvert.SerializeObject(account, settings);         Console.WriteLine(json); 
like image 82
tia Avatar answered Sep 29 '22 18:09

tia


Luckily, Newtonsoft.Json has an override on the JsonConvert.SerializeObject() method that allows us to provide a type, so that the resulting JSON doesn't contain properties that don't exist in that type. So, to eliminate properties, you can make a safe copy of your Account class with all the sensitive properties removed, and give it a different name:

public class AccountJSON {     public string FullName { get; set; }     public string EmailAddress { get; set; } } 

Provide its type when serializing:

var TheAccount = DBContext.Accounts.Find(1); var TheJSON = Newtonsoft.Json.JsonConvert.SerializeObject(TheAccount, typeof(AccountJSON)); 

Note: This may only work on the first level deep when the serializer travels through the object. If the Account object has lazy loading properties that reference even more Account objects, they may not use the "safe" type that you originally provided.

like image 32
user3163495 Avatar answered Sep 29 '22 16:09

user3163495