返回为json时排除某些字段 [英] Exclude certain fields when returning as json
问题描述
我有一个asp.net网络api应用程序.
现在让我们说应用程序由一个User实体和一个Post实体组成. 帖子是由用户撰写的,因此每个帖子实体都包含对该用户实体的引用.
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
}
问题是当我想以Json的身份返回帖子列表时. 我不想在列表中包括帖子的作者,换句话说,我想从帖子列表中排除用户"字段.
示例:
[
{
"Id": 1,
"Title": "Post A",
"Content": "..."
},
{
"Id": 2,
"Title": "Post B",
"Content": "..."
}
]
我知道我可以轻松地做到这一点,方法是创建一个不带User字段的名为JsonPost的新类,然后使用linq将Post的列表转换为JsonPost的列表,但是我想在不创建新类的情况下解决它. /p>
谢谢, 阿里克
只需使用Newton.Json命名空间中的[JsonIgnore]属性标记Post的User属性,它将不会被序列化
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
}
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
}
这篇关于返回为json时排除某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!