0

I'm building a RESTful web service in c#.

So I have build this DTo Model like this:

namespace WebService.Models
{
    [DataContract(Name = "VitalSigns")]
    public class VitalSignsDTO
    {
        [DataMember(Name = "id", Order = 1)]
        public int id { get; set; }

        [DataMember(Name = "name", Order = 2)]
        public string name { get; set; }

        [DataMember(Name = "valore", Order = 3)]
        public string valore { get; set; }

        [DataMember(Name = "dataOra", Order = 3)]
        public DateTime? dataOra { get; set; }
    }
}

Now, this is the response of JSON:

{
    "id": 1,
    "name": "Altezza corporea",
    "valore": null,
    "dataOra": null
},
{
    "id": 2,
    "name": "Peso corporeo",
    "valore": null,
    "dataOra": null
}

now I want to know, if is possible to hidden valore and dataOra field that not have a value.

Jaliya Udagedara
  • 1,087
  • 10
  • 16
bircastri
  • 2,169
  • 13
  • 50
  • 119
  • Possible duplicate of [How to ignore a property in class if null, using json.net](https://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net) – mjwills Feb 13 '18 at 12:13
  • If you are returning an array/collection of json objects I don't think you want to omit fields because it will make it more difficult for the consumer to deal with some that are there and some that are not. – Crowcoder Feb 13 '18 at 12:14

2 Answers2

0

use [JsonIgnore] attribute to your property.

namespace WebService.Models
{
    [DataContract(Name = "VitalSigns")]
    public class VitalSignsDTO
    {
        [DataMember(Name = "id", Order = 1)]
        public int id { get; set; }

        [DataMember(Name = "name", Order = 2)]
        public string name { get; set; }

        [JsonIgnore]
        [DataMember(Name = "valore", Order = 3)]
        public string valore { get; set; }

        [JsonIgnore]
        [DataMember(Name = "dataOra", Order = 3)]
        public DateTime? dataOra { get; set; }
    }
}
Jaliya Udagedara
  • 1,087
  • 10
  • 16
programtreasures
  • 4,250
  • 1
  • 10
  • 29
0

If you are in .Net Core WebAPI, you can configure JSON Serializer in the middleware (Startup.cs).

   public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
                .AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; });
        services.AddAutoMapper();
        services.RegisterServices();
    }

If you are in ASP.NET WebAPI, refer Suppress properties with null value on ASP.NET Web API

Arun Selva Kumar
  • 2,593
  • 3
  • 19
  • 30