Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonIgnore attributes not working in ASP.NET?

I've got an object in my project with circular references. I've put [JsonIgnore] above the field like so:

    [JsonIgnore]     public virtual Foobar ChildObject { get; set; } 

I'm still getting circular reference errors when I serialize the object. The only fields that do not have JsonIgnore are string fields and should not cause this. Is there something else I need to do to get JsonIgnore to work?

Thanks!

like image 843
chum of chance Avatar asked Jun 01 '10 23:06

chum of chance


People also ask

What is JsonIgnore attribute?

Ignore individual properties 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. If no Condition is specified, this option is assumed.

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.

Does Newtonsoft JSON support .NET core?

ASP.NET Core 3.0 and above Newtonsoft JSON is available as NuGet Package.


1 Answers

I had incorrectly resolved the JsonIgnore reference.

Note that this attribute exists in more than one namespace:

  • System.Text.Json.Serialization
  • Newtonsoft.Json

I had resolved this in VS to System.Text.Json.Serialization.JsonIgnore - however I was using the Newtonsoft library for my actual Serialise/Deserialise - and hence the attribute was ignored. Changing the reference to Newtonsoft.Json.JsonIgnore resolved.

like image 142
user369142 Avatar answered Sep 30 '22 18:09

user369142