以json格式返回时排除某些字段

时间:2015-08-16 16:45:56

标签: c# asp.net json asp.net-web-api

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

示例:

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

我知道我可以通过在没有User字段的情况下创建一个名为JsonPost的新类,然后使用linq将Post的列表转换为JsonPost列表来轻松完成,但我想解决它没有创建一个新类。

谢谢, 阿里克

2 个答案:

答案 0 :(得分:4)

只需使用Newtonsoft.Json命名空间中的[JsonIgnore]属性标记Post的用户属性,它就不会被序列化

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
} 

答案 1 :(得分:1)

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