Hide virtual ICollection Property From WebApi Result

Prathamesh Shende 381 Reputation points
2021-06-14T07:05:29.507+00:00

Hello,
My model is like this

public class Emp
{
public int ID {get;set;}
public string Name {get;set;}
public int DepartmentID {get;set;}
public Department Department {get;set;}
}

public class Department
{
Department()
{
emps = new HashSet<Emp>();
}
public int ID { get;set; }
public string Name {get;set;}
public virtual ICollection<Emp> emps {get;set;}
}

after I Getting reponse in json format by running GetALL Api for department.

It shows
Department.json result
{

"name": "Income Tax",
"Emps": [] // want to hide this
}
So, I want to hide emps: []

how to do this?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,522 questions
{count} votes

Accepted answer
  1. Chao Deng-MSFT 796 Reputation points
    2021-06-15T08:55:57.703+00:00

    Hi @PrathameshShende-2581 ,

    To ignore individual properties, you can use the [JsonIgnore] attribute,like this:
    Model:

      public class Emp  
        {  
            public int ID { get; set; }  
            [JsonIgnore]  
            public string Name { get; set; }  
            
        }  
    

    c#

    Emp emp = new Emp()  
                {  
                    ID = 1,  
                    Name = "Test"  
                };  
               var json = JsonSerializer.Serialize(emp);  
                Console.WriteLine(json);  
    

    Result:
    eS7dY.png

    For more ignored properties of System.Text.Json, you can refer to the official documentation for viewing.
    How to ignore properties with System.Text.Json


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    ChaoDeng

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Duane Arnold 3,221 Reputation points
    2021-06-14T09:10:57.797+00:00
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.