0

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();
}
Pankaj
  • 2,618
  • 3
  • 25
  • 47
  • You can make the age property nullable, it will still return it but it will be null instead of 0. Other than that I don't think its posible. – Dmyto Holota Jul 22 '22 at 09:55
  • After 5 min search io found this that my be useful: https://stackoverflow.com/a/70980234/6895130 you can specify the json converter to ignore null fields. – Dmyto Holota Jul 22 '22 at 09:57

1 Answers1

2

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.

Dmyto Holota
  • 356
  • 1
  • 4
  • 14