0

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.

1
  • [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] see: docs Commented Jun 20, 2022 at 11:21

1 Answer 1

1

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)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.