Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 作为json返回时排除某些字段_C#_Asp.net_Json_Asp.net Web Api - Fatal编程技术网

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

C# 作为json返回时排除某些字段,c#,asp.net,json,asp.net-web-api,C#,Asp.net,Json,Asp.net Web Api,我有一个asp.net web api应用程序 现在让我们假设应用程序由一个用户实体和一个Post实体组成。 帖子由用户编写,因此每个帖子实体都包含对用户实体的引用 class Post { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public User User { get; set; } // R

我有一个asp.net web api应用程序

现在让我们假设应用程序由一个用户实体和一个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的新类(不带User字段),然后使用linq将Post的列表转换为JsonPost的列表来轻松实现这一点,但我想在不创建新类的情况下解决它

谢谢,
Arik

只需使用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
} 

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