JsonIgnore attributes not working in ASP.NET?

35,440

Solution 1

You likely have some other property that links back to its parent. Use the ReferenceLoopHandling.Ignore setting to prevent self-referencing loops.

using Newtonsoft.Json;

JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

string json = JsonConvert.SerializeObject(foobars, Formatting.None, jsSettings);

Solution 2

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.

Solution 3

If anyone needs an ASP.Net Core implementation of ignore child references, here it is.

public void ConfigureServices(IServiceCollection services)
{
...

    services.AddMvc()


         .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}

src: https://docs.microsoft.com/en-us/ef/core/querying/related-data

Share:
35,440
chum of chance
Author by

chum of chance

Updated on January 09, 2021

Comments

  • chum of chance
    chum of chance over 3 years

    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!