DefaultValueHandling not enforced in Json.NET 4.5

I am using JSON.NET 4.5 and following this post trying to properly serialize my objects.

I hit my head against the wall for hours; no matter what I do, I can not get Json.NET to ignore ints when they are set to "standardized uniform value for this value type", aka 0.

[DataContract] public class User { [DataMember] public int Id { get; set; } [DataMember] public string Name{ get; set; } [DataMember] public string Email{ get; set; } } 

Serialization is called here:

 var user = new User() { Id = 0, Name = "John Doe", Email = null } string body = JsonConvert.SerializeObject(user, Formatting.Indented, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }); 

Resulting JSON:

 { "Id": 0, "Name": "John Doe" } 

Email is omitted because it is zero. The identifier must be omitted since it is 0. I also tried to explicitly set the [DefaultValue (0)] attribute in Id so as not to affect.

Am I doing something wrong or is it a mistake?

Update

After another look, the DefaultValueAtribute function executed for ints. Thus, this code will cause identifiers 0 not to be serialized.

 [DataContract] public class User { [DataMember] [DefaultValue(0)] public int Id { get; set; } [DataMember] public string Name{ get; set; } [DataMember] public string Email{ get; set; } } 

Not declared behavior, but at least it allows me to continue my life.

+6
source share
1 answer

This seems to be a mistake. According to the example in the documentation, the DefaultValueAttribute attribute is not required. This is useful, for example, when you cannot edit the type you are serializing.

I made a problem on Github for it, as well as a patch / hack (versus 4.5r8).

+1
source

Source: https://habr.com/ru/post/920633/


All Articles