Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DefaultValueHandling not honored in Json.NET 4.5

Tags:

.net

json.net

I'm using JSON.NET 4.5 and following this blog post, trying to get my user objects to serialize correctly.

I've been beating my head against the wall for hours; no matter what I do, I cannot get Json.NET to ignore ints when they are set to the "default unitialized value for that 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; }        
}

Here's the call to serialize it:

var user = new User()
{
    Id = 0,
    Name = "John Doe",
    Email = null
}

string body = JsonConvert.SerializeObject(user, Formatting.Indented, new JsonSerializerSettings()
{
    DefaultValueHandling = DefaultValueHandling.Ignore
});

The resulting JSON is:

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

Email is omitted because it is null. Id should be omitted because it is 0. I have also tried explicitly setting the [DefaultValue(0)] attribute on Id, to no effect.

Am I doing something wrong, or is this a bug?

Update

After taking another look, DefaultValueAtribute is being honored for ints. So this code will result Ids of 0 not being 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 the stated behavior, but at least it allows me to get on with my life.

like image 606
Brian Issleb Avatar asked Jul 16 '12 22:07

Brian Issleb


1 Answers

It appears to be a bug. According to the example from documentation a DefaultValueAttribute shouldn't be required. This is useful e.g. when you can't edit the type you're serializing.

I made an issue in Github for it, along with a patch/hack (against 4.5r8).

like image 99
johv Avatar answered Nov 09 '22 03:11

johv