简体   繁体   中英

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

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.

I use the ScriptIgnore attribute on my model like so:

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 SO when I was turned on to the difference between a Model and ViewModel.

[ScriptIgnore] 

是你的huckaberry。

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

Here a portion of my text template before

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM