-1

I have a rest service that returns a json. Everything is working and i was wondering if i could ignore null values in respose because i don't want to send something like:

{
"name": "George",
"country": null,
"city": null
}

I would like to return something like:

{
"name": "George"
}

The object that represents a Client is like that:

namespace Tests.Domain
{

public class Client
{
    public Client() { }

    [DataMember]
    public string Name{ get; set; }
    [DataMember]
    public Country Country { get; set; }
    [DataMember]
    public City City { get; set; }

}
}

And my response is:

...
return Request.CreateResponse((HttpStatusCode)200, clientSession);

Thanks in advance.

David L.

Liam
  • 27,717
  • 28
  • 128
  • 190
  • i'm not using JSonNet to serialize.. –  May 16 '14 at 20:40
  • Does this answer your question? [Suppress properties with null value on ASP.NET Web API](https://stackoverflow.com/questions/14486667/suppress-properties-with-null-value-on-asp-net-web-api) – Liam Sep 08 '21 at 08:07

1 Answers1

1

In your WebApiConfig.Register method, add the following code after route registration code:

   var jsonConfig = config.Formatters.JsonFormatter;
   jsonConfig.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
Toan Nguyen
  • 11,263
  • 5
  • 43
  • 59