Ryan
Ryan

Reputation: 5546

WCF JSON - do not return those fields which are null al all

I have to return trough Json an object like this:

User={
    id:4,
    name:'Peter',
    nickname:null
}

So my C# object looks like:

class User {
    public int Id {get;set;} 
    public string name {get;set;} 
    public string nickname {get;set;} 
}

WCF automaticly translated the C# obkect to the Json above. But If nickname is null, how can I tell WCF not to return it at all, so the JSOn returned would be

User={
    id:4,
    name:'Peter'
}

Upvotes: 2

Views: 333

Answers (1)

Juri
Juri

Reputation: 32900

As far as I know WCF uses the DataContractJsonSerializer for serializing objects to JSON. Usually you have there a class annotated with DataMember attributes which again have an EmitDefaultValue property (default is true; see docs here)

Gets or sets a value that specifies whether to serialize the default value for a field or property being serialized.

So it might work if you do something like the following:

[DataContract]
class User {

    [DataMember]
    public int Id {get;set;} 

    [DataMember]
    public string name {get;set;} 

    [DataMember(EmitDefaultValue=false)]
    public string nickname {get;set;} 
}

Note, I didn't try this by myself. You'd have to check, but it sounds like it could work.

Upvotes: 4

Related Questions