简体   繁体   中英

How to hide the nested class in Web API Model ASP.NET

I am trying to hide a nested class from a Web API response if that nested classes is null.

Please find the Web API model below:

    public class School {
       public Student students {get; set;}
       public Teacher teachers {get; set;}
    }

    public class Student {
       public string id {get; set;}
       public string name {get; set;}
    }

    public class Teacher {
       public string id {get; set;}
       public string name {get; set;}
    } 

Postman Response (if the teacher value is null):

    {
      students: {
          id: "1234",
          name: "Alex"
      },
    teachers: null
    }

But my expected response is:

{
  students: {
      id: "1234",
      name: "Alex"
  }
}

I've tried [DataMember(EmitDefaultValues = False)], [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] but nothing worked. Please advice me how to hide the inner class model if it is null.

You don't need to specify null value handling for every property. There are a few ways you could do it.

you can add it in the Startup.cs

 services.AddControllers()
           .AddJsonOptions(opt =>
           {
               opt.JsonSerializerOptions.IgnoreNullValues = true;
           });

If using NewtonsoftJson

services.AddControllers().AddNewtonsoftJson(options => 
   options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore);

Or in the class

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
// or
[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]

// or for all properties in a class
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM