Search code examples
c#apiasp.net-web-apiazure-api-apps

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?


Solution

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

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