I have an asp.net web api application.
For now lets say that the application consists of a User entity and a Post entity. A post is written by a user, so every post entity contains a reference to the user entity.
class Post {
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public User User { get; set; } // Reference to the user that wrote the post
}
The problem is when i want to return a list of posts as Json. I don't want to include the writers of the posts inside the list, in other words, i want to exclude the User field from the list of posts.
Example:
[
{
"Id": 1,
"Title": "Post A",
"Content": "..."
},
{
"Id": 2,
"Title": "Post B",
"Content": "..."
}
]
I know that i can do it easily by creating a new class called JsonPost without the User field and then converting the list of Post's to a list of JsonPost's with linq, but i want to solve it without creating a new class.
Thanks, Arik
Just mark Post's User property with [JsonIgnore] attribute from Newtonsoft.Json namespace and it won't be serialized
using Newtonsoft.Json;
class Post {
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
[JsonIgnore]
public User User { get; set; } // This property won't be serialized
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With