question

PrathameshShende avatar image
0 Votes"
PrathameshShende asked ChaoDeng-MSFT answered

Hide virtual ICollection Property From WebApi Result

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?

dotnet-aspnet-core-webapi
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Use the JsonIgnore attribute.


0 Votes 0 ·
ChaoDeng-MSFT avatar image
0 Votes"
ChaoDeng-MSFT answered

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


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.