Newtonsoft.Json icon indicating copy to clipboard operation
Newtonsoft.Json copied to clipboard

MissingMemberHandling.Error doesn't throw when property is set with jsonignore

Open vsudhini opened this issue 2 years ago • 1 comments

public class Account { public string FullName { get; set; } public bool Deleted { get; set; } [JsonIgnore] public bool DeletedDate{ get; set; } }

string json = @"{ 'FullName': 'Dan Deleted', 'Deleted': true, 'DeletedDate': '2013-01-20T00:00:00' }";

try { JsonConvert.DeserializeObject<Account>(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); } catch (JsonSerializationException ex) //No Error returned {

Console.WriteLine(ex.Message);

}

after setting MissingMemberHandling.Error does not seem to throw serialization exception for a property set with jsonignore how to handle this?

Source/destination types

// Put the types you are serializing or deserializing here

Source/destination JSON

{"message":"Place your serialized or deserialized JSON here"}

Expected behavior

Actual behavior

Steps to reproduce

// Your calls to Newtonsoft.Json here

vsudhini avatar Jan 29 '24 15:01 vsudhini

That there is no exception being thrown for ignored members is logical and expected behavior and no bug. Because the member is not missing, it is just ignored.

One relatively easy way to make an ignored member go "missing" is to create your own contract resolver derived from DefaultContractResolver, which removes ignored properties from the list of properties for an object contract. Something like this, for example:

class IgnoredMembersGoMissingContractResolver : DefaultContractResolver
{
  protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    => base.CreateProperties(type, memberSerialization)
           .Where(p => !p.Ignored)
           .ToList();
}

I haven't tested this code myself (just written down from the top of my head, and therefore might contain typos or other errors), but it can serve as an illustration of the approach.

Note that the JsonProperty.Ignored value tested here is not only influenced by the JsonIgnoreAttribute, but also by other attributes.

Especially noteworthy is that JsonProperty.Ignored is also set by the JsonExtensionDataAttribute. If you are using this attribute, you will have to test thoroughly whether "blindly" removing the extension data property from the list of serializable properties (as my code example does) has any averse side effects.

elgonzo avatar Jan 30 '24 09:01 elgonzo