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.
source share