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();
}
2
  • 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. Commented Jul 22, 2022 at 9:55
  • After 5 min search io found this that my be useful: stackoverflow.com/a/70980234/6895130 you can specify the json converter to ignore null fields. Commented Jul 22, 2022 at 9:57

1 Answer 1

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.

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.