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.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.
You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.
Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects. In this article and code examples, first we will learn how to serialize JSON in C# and then we will learn how to deserialize JSON in C#.
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]
is your huckaberry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With