Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent JSON serialization in ASP.NET MVC?

While developing an ASP.NET MVC app, I'm finding a few places where my JsonResult actions throw an exception "A circular reference was detected while serializing an object".

For now, I'm removing the references in question, but ideally I'd like to simply mark the property such that the JSON serializer ignores it.

Can anyone suggest how I might do this?

like image 739
JMP Avatar asked Aug 12 '09 22:08

JMP


People also ask

How do I ignore a JSON property?

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.

How do you turn off or handle Camelcasing in JSON response in asp net core?

You have to change the DefaultContractResolver which uses camelCase by default. Just set the NamingStatergy as null . This should be done in the StartUp.

Do we need to serialize JSON?

The purpose of serializing it into JSON is so that the message will be a format that can be understood and from there, deserialize it into an object type that makes sense for the consumer.

Can I optionally turn off the JsonIgnore attribute at runtime?

Yes, this can be done using a custom ContractResolver . You didn't show any code, so I'll just make up an example. Let's say I have a class Foo as shown below.


1 Answers

[ScriptIgnore] should work for you.

like image 197
Marc Avatar answered Oct 02 '22 18:10

Marc