作为json返回时排除某些字段

本文关键字:字段 排除 json 返回 作为 | 更新日期: 2023-09-27 18:08:15

我有一个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的帖子列表。我不想在列表中包含文章的作者,换句话说,我想从文章列表中排除User字段。

的例子:

[
    {
        "Id": 1,
        "Title": "Post A",
        "Content": "..."
    },
    {
        "Id": 2,
        "Title": "Post B",
        "Content": "..."
    }
]

我知道我可以通过创建一个名为JsonPost的新类而不带用户字段,然后将Post的列表转换为使用linq的JsonPost列表来轻松地做到这一点,但我想在不创建新类的情况下解决它。

谢谢,Arik

作为json返回时排除某些字段

用Newtonsoft的[JsonIgnore]属性标记Post的User属性。Json命名空间,不会被序列化

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
} 

由于您不想创建视图模型,另一种方法是使用投影。或者创建一个动态对象