TusharJ
TusharJ

Reputation: 1263

Dynamically remove properties from api response

I have a api whose response is as below
"prop1": "SomeValu1",
"prop2": "SomeValue2",
"prop3": null,
"prop4": "SomeValue4"

The problem is, based on input some of the properties will be null(expected behavior) which i don;t want to return in the response. Something like this (prop3 is not there)

"prop1": "SomeValu1",
"prop2": "SomeValue2",
"prop4": "SomeValue4"

Which property will be null is based on runtime logic. Any ideas how can i do this?

Upvotes: 1

Views: 3572

Answers (2)

Igor
Igor

Reputation: 3194

DataContract attribute has property called EmitDefaultValue if you set it to false it will not be serialized.

If you add those attributes in your Dto class you will get functionality that you are asking for. https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.emitdefaultvalue(v=vs.110).aspx

Example:

[DataContract]
public class ExampleDto
{
    [DataMember(Name="prop1", EmitDefaultValue=false)]
    public string Prop1 {get;set;}
    [DataMember(Name="prop2", EmitDefaultValue=false)]
    public string Prop2 {get;set;}
    [DataMember(Name="prop3", EmitDefaultValue=false)]
    public string Prop3 {get;set;}
    [DataMember(Name="prop4", EmitDefaultValue=false)]
    public string Prop4 {get;set;}
}

You can even use property Name to change it's name when serializing.

Upvotes: 0

Aashish Kumar
Aashish Kumar

Reputation: 1643

If you are working on JSON then You can try this:

JsonConvert.SerializeObject(yourObject, 
                        Newtonsoft.Json.Formatting.None, 
                        new JsonSerializerSettings { 
                            NullValueHandling = NullValueHandling.Ignore
                        });

Upvotes: 8

Related Questions