JsonIgnore 属性在 ASP.NET 中不起作用?

问题描述 投票:0回答:4

我的项目中有一个带有循环引用的对象。我已将 [JsonIgnore] 放在字段上方,如下所示:

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

当我序列化对象时,我仍然遇到循环引用错误。唯一没有 JsonIgnore 的字段是字符串字段,不应导致这种情况。我还需要做些什么才能让 JsonIgnore 正常工作吗?

谢谢!

c# asp.net asp.net-mvc json json.net
4个回答
85
投票

我错误地解析了 JsonIgnore 引用。

请注意,该属性存在于多个命名空间中:

  • System.Text.Json.序列化
  • Newtonsoft.Json

我已在 VS 中将其解决为 System.Text.Json.Serialization.JsonIgnore - 但是我使用 Newtonsoft 库进行实际的序列化/反序列化 - 因此该属性被忽略。 更改对 Newtonsoft.Json.JsonIgnore 的引用已解决。


34
投票

您可能还有一些其他属性链接回其父级。使用

ReferenceLoopHandling.Ignore
设置可防止自引用循环。

using Newtonsoft.Json;

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

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

4
投票

如果有人需要忽略子引用的 ASP.Net Core 实现,这里就是。

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/lated-data


0
投票

使用这个解决了我的问题

using System.Text.Json.Serialization;
© www.soinside.com 2019 - 2024. All rights reserved.