我的ASP.NET MVC项目中有一个这样的简单实体:
public class Folder : EntityData
{
public Folder()
{
IsStub = false;
}
[StringLength(300)]
public string Name { get; set; }
[JsonIgnore]
public bool IsStub { get; set; }
[ForeignKey("ParentFolderObj")]
public string ParentFolder { get; set; }
[JsonIgnore]
public Folder ParentFolderObj { get; set; }
[JsonIgnore]
public virtual ICollection<DesktopFolder> DesktopFolders { get; set; }
[JsonIgnore]
public virtual ICollection<UserFolder> UserFolders { get; set; }
}
EntityData是Azure的MobileAppServices SDK提供的类:
public abstract class EntityData : ITableData
{
protected EntityData();
[Key]
[TableColumn(TableColumnType.Id)]
public string Id { get; set; }
[TableColumn(TableColumnType.Version)]
[Timestamp]
public byte[] Version { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Index(IsClustered = true)]
[TableColumn(TableColumnType.CreatedAt)]
public DateTimeOffset? CreatedAt { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[TableColumn(TableColumnType.UpdatedAt)]
public DateTimeOffset? UpdatedAt { get; set; }
[TableColumn(TableColumnType.Deleted)]
public bool Deleted { get; set; }
}
在我的序列化响应中,例如当我检索所有文件夹时,我仍然看到字段&#34; IsStub&#34;即使它被标记为[JsonIgnore]。
我正在使用Newtonsoft.Json来(取消)序列化,以下配置适用于所有项目并在启动时设置:
HttpConfiguration config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
正如您所看到的,还有其他[JsonIgnore]字段,这些字段在响应中没有正确显示,如下所示:
{
"deleted": false,
"updatedAt": null,
"createdAt": "2018-06-03T06:13:31.66Z",
"version": "AAAAAAAACJc=",
"id": "042d81b8-4599-43ec-b462-8cbaf6ecd672",
"parentFolder": null,
"isStub": false,
"name": "Folder636636104113385950"
}
如何让字段"IsStub"
从我的回复中消失?
我还试图用[ScriptIgnore]
标记该字段,但没有运气。
答案 0 :(得分:0)
将以下内容添加到您的“ EntityData ”类中:
public virtual bool ShouldSerializeIsStub()
{
return true;
}
像这样覆盖“ 文件夹”类中的函数:
public override bool ShouldSerializeIsStub()
{
return false;
}
[JsonIgnore]“标签”(它是标签吗?)是正确的。 其余的都还可以。这对我来说很好。希望对您也一样。