问题
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
回答1:
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
}
回答2:
Since you don't want to create a view model another way would be by using projection. Or creating a dynamic object.
来源:https://stackoverflow.com/questions/32037555/exclude-certain-fields-when-returning-as-json