Home > Net >  Conditional ignore a property while calling Web API
Conditional ignore a property while calling Web API

Time:07-22

I want to ignore one property while returning data from Web API call. Here is my class.

public class Customer 
{
    public Customer(int id, string name)
    {
       ID = id;
       Name = name;
    }

    public Customer(int id, string name, int age)
    {
       ID = id;
       Name = name;
       Age = age;
    }

    int Id {get; set}
    string Name {get; set}
    int Age {get; set}
 }

and here are Apis in the Controller class

Customer GetCustomerById(int id)
{
    var customer = GetCustomerData();
    // I want to return only Id and Name, but it is returning age also with value 0
    return new Customer(customer.id, customer.Name);    
}


List<Customer> GetCustomerByName(string name)
{
    var customers = GetCustomerDataByName(name); 
    // Over here I need all three properties, hence I am not using JsonIgnore on Age Property
    return customers.Select(x => new Customer(x.id, x.name, x.age)).ToList();
}

CodePudding user response:

You can change the age properly to be nullable int?. And then configure the json converter to ignore null params:

services.AddMvc()
.AddJsonOptions(options =>
{
    options.JsonSerializerOptions.IgnoreNullValues = true;
});

for more info look here.

  • Related