C# 在 .NET JSON 序列化期间忽略字段;类似于 [XmlIgnore]?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1411577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:16:08  来源:igfitidea点击:

Ignoring a field during .NET JSON serialization; similar to [XmlIgnore]?

c#.netasp.net-mvcjsonserialization

提问by runxc1 Bret Ferrier

I have a POCO class that is being sent to the browser as a JSON string in .NET 3.5 sp1. I am just using the default JSON serialization and I have some fields that I want to ignore. I want to put an attribute similar to [System.Xml.Serialization.XmlIgnore] on them so that they are not serialized.

我有一个 POCO 类,它作为 .NET 3.5 sp1 中的 JSON 字符串发送到浏览器。我只是使用默认的 JSON 序列化,我有一些我想忽略的字段。我想在它们上面放置一个类似于 [System.Xml.Serialization.XmlIgnore] 的属性,这样它们就不会被序列化。

采纳答案by JMP

I use the ScriptIgnoreattribute on my model like so:

我在我的模型上使用ScriptIgnore属性,如下所示:

public class Item
{
    [ScriptIgnore]
    public Item ParentItem { get; set; }
}

In this particular scenario I was getting a circular reference error from the Json serializer, so I simply ignored it. I was asking a similar question here on SOwhen I was turned on to the difference between a Model and ViewModel.

在这个特定的场景中,我从 Json 序列化器中得到了一个循环引用错误,所以我只是忽略了它。我在这里问的SO类似的问题,当我开到模型和视图模型之间的区别。

回答by Wyatt Barnett

[ScriptIgnore] 

is your huckaberry.

是你的哈卡贝里。

回答by Alex Boutin Flegel

You just need to add the [ScriptIgnore(ApplyToOverrides = true)]into your text template (.tt) file.

您只需要将 加入 [ScriptIgnore(ApplyToOverrides = true)]到您的文本模板 (.tt) 文件中。

Here a portion of my text template before

这是我之前的文本模板的一部分

#>
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#

Once I inserted the code the line above the codeStringGeneratormy classes auto generated and looked like this:

一旦我在codeStringGenerator我的类自动生成的上面插入了代码,看起来像这样:

[ScriptIgnore(ApplyToOverrides = true)]
public virtual ICollection<Currency> Currencies { get; set; }

I also needed to modify the UsingDirectivesfunction to insert "using System.Web.Script.Serialization;"

我还需要修改UsingDirectives函数以插入"using System.Web.Script.Serialization;"

回答by hakan

Set property as internal. Depends on your structure, though. Take into consideration.

将属性设置为内部。不过,这取决于您的结构。考虑到。