我有一个 ASP.NET Web 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 形式返回帖子列表时。
我不想将帖子的作者包含在列表中,换句话说,我想从帖子列表中排除“用户”字段。
Example:
[
{
"Id": 1,
"Title": "Post A",
"Content": "..."
},
{
"Id": 2,
"Title": "Post B",
"Content": "..."
}
]
我知道我可以通过创建一个不带 User 字段的名为 JsonPost 的新类,然后使用 linq 将 Post 列表转换为 JsonPost 列表来轻松完成此操作,但我想在不创建新类的情况下解决它。
谢谢,
阿里克
只需使用 Newtonsoft.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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)