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

C#.Netasp.net MvcJsonSerialization

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

I use the http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx">ScriptIgnore</a> 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 https://stackoverflow.com/questions/1269106/how-do-i-prevent-json-serialization-in-asp-net-mvc">asking a similar question here on SO when I was turned on to the difference between a Model and ViewModel.

Solution 2 - C#

[ScriptIgnore] 

is your huckaberry.

Solution 3 - C#

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;"

Solution 4 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrunxc1 Bret FerrierView Question on Stackoverflow
Solution 1 - C#JMPView Answer on Stackoverflow
Solution 2 - C#Wyatt BarnettView Answer on Stackoverflow
Solution 3 - C#Alex Boutin FlegelView Answer on Stackoverflow
Solution 4 - C#hakanView Answer on Stackoverflow