开发者

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开发者_C百科 something else I need to do to get JsonIgnore to work?

Thanks!


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.


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://learn.microsoft.com/en-us/ef/core/querying/related-data

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜