Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 826
runxc1 Bret Ferrier Avatar asked Sep 11 '09 15:09

runxc1 Bret Ferrier


People also ask

How do I ignore properties in JSON?

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.

Which of the following attribute should be used to indicate the property must not be serialized while using .JSON serializer?

Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.

How can you prevent a property from being 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.

What is serialization of JSON in C#?

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#.


2 Answers

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.

like image 144
JMP Avatar answered Sep 20 '22 21:09

JMP


[ScriptIgnore]  

is your huckaberry.

like image 21
Wyatt Barnett Avatar answered Sep 21 '22 21:09

Wyatt Barnett