【问题标题】:JsonIgnore attributes not working in ASP.NET?JsonIgnore 属性在 ASP.NET 中不起作用?
【发布时间】:2011-02-26 14:21:03
【问题描述】:

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

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

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

谢谢!

【问题讨论】:

  • 刚放假回来,今晚我会看看这个,让你知道。谢谢!
  • 也可以使用[ScriptIgnore],因为[JsonIgnore]好像没有实现。
  • 有关 JsonIgnore 为何不起作用的更多信息。您可能需要了解 ASP.NET WebAPI 和 ASP.NET MVC 之间的区别。 * 为什么 JsonIgnore 不起作用:两者使用的不一样请同时参考以下答案。序列化器。 stackoverflow.com/questions/32160530/… 这个:stackoverflow.com/questions/14591750/… *btw,sry,我想把这个引用指向 cmets,但没有这样做的声誉

标签: c# asp.net asp.net-mvc json json.net


【解决方案1】:

我错误地解析了 JsonIgnore 引用。

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

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

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

【讨论】:

    【解决方案2】:

    您可能还有一些其他属性链接回其父级。使用ReferenceLoopHandling.Ignore 设置来防止自引用循环。

    using Newtonsoft.Json;
    
    JsonSerializerSettings jsSettings = new JsonSerializerSettings();
    jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    
    string json = JsonConvert.SerializeObject(foobars, Formatting.None, jsSettings);
    

    【讨论】:

    • 我一直在到处寻找这个;多次提到 Newtonsoft 支持忽略循环引用并且没有提及要设置的实际属性。谢谢!
    • 谢谢 但是我如何继续使用JSon(models,"text/json",JsonRequestBehavior.AlloGet)
    • @Bellash 我不知道你在问什么。
    • @Bellash,你可以使用类似return Content(JsonConvert.SerializeObject(foobars, Formatting.None, jsSettings), "application/json");
    • 这似乎是必要的,即使您在包含循环的属性上使用 [JsonIgnore]。
    【解决方案3】:

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

    public void ConfigureServices(IServiceCollection services)
    {
    ...
    
        services.AddMvc()
    
    
             .AddJsonOptions(
                options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            );
    
        ...
    }
    

    源代码:https://docs.microsoft.com/en-us/ef/core/querying/related-data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      • 2021-07-24
      相关资源
      最近更新 更多