JsonIgnore attributes not working in ASP.NET?
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);
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
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.