【问题标题】:The new ASP.NET Core 3.0 Json serializer is leaving out data新的 ASP.NET Core 3.0 Json 序列化器遗漏了数据
【发布时间】:2020-02-06 21:30:41
【问题描述】:

我正在将一个 Web 应用程序移植到 ASP.NET Core 3,经过一番折腾,我快到了终点。一切似乎都正常,但突然间我从 api 返回的 JSON 数据丢失了一些级别。

options.JsonSerializerOptions.MaxDepth 似乎默认为 64 级,所以可以这样。在其他一些地方,选项可能会欺骗我?

这是代码(以及值的快速查看):

这是我在浏览器中得到的 JSON:

因此,生成的输出中完全缺少 ParticipantGroups 属性/集合。

发生这种情况的任何想法?

编辑:

我在 Github 上添加了一个展示该问题的存储库。标准 ASP.NET Core 3.0 解决方案,从模板创建,对 Weatherforecast 控制器返回的结果进行了更改:

https://github.com/steentottrup/systemtextjsonissue

【问题讨论】:

  • 请将您的代码/JSON 显示为文本,而不是图像。并在您的问题中包含相关的类定义(同样,作为文本)。

标签: asp.net-core jsonserializer asp.net-core-3.0


【解决方案1】:

现在我已经回到使用 Newtonsoft.Json 和 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包。然后当我有时间时,我会尝试找出解决方案是什么,没有 Newtonsoft.Json。

【讨论】:

  • 这不是 IMO 对这个问题的回答。这只是你所做的以继续工作。我会删除这个“答案”,因为它并没有真正的帮助。如果您有机会,我也会尝试用更多代码示例更新初始帖子,以便我们都可以尝试为您提供更多帮助。
  • 出于这个原因我还没有接受它,但对于某些人来说,比如我现在,这可能是解决问题的方法。
  • @Pure.Krome in .Net 6 System.Text.Json 仍然没有与Newtonsoft 100% 对等。如果您对System.Text.Json 有疑问,那么改用Newtonsoft 仍然是一个可行且可接受的解决方案。 OP 没有专门要求使用 System.Text.Json 的解决方案
【解决方案2】:

这个问题好像是新版本3.0的错误。至少在我看来这是一个错误。

似乎System.Text.Json 将转换层次结构中提到的类,而不是实际的类。所以如果你在层次结构中使用抽象类,你就有麻烦了。第二次我删除了基类,并使用了我要返回的实际类,问题似乎就消失了。

所以这不起作用:

public class SurveyReportResult {
    public Guid Id { get; set; }
    public String Name { get; set; }
    public Int32 MemberCount { get; set; }
    public IEnumerable<OrganisationalUnit> OrganisationalUnits { get; set; }
}

public abstract class OrganisationalUnit {
    public Guid Id { get; set; }
    public String Name { get; set; }
    public Int32 MemberCount { get; set; }

}

public class OrganisationalUnitWithParticipantGroups : OrganisationalUnit {
    public IEnumerable<ParticipantGroup> ParticipantGroups { get; set; }
}

public class ParticipantGroup {
    public Guid Id { get; set; }
    public String Name { get; set; }
    public Int32 MemberCount { get; set; }
}

这只会返回OrganisationalUnit 类的属性,而不是OrganisationalUnitWithParticipantGroups 的附加属性。

这行得通:

public class SurveyReportResult {
    public Guid Id { get; set; }
    public String Name { get; set; }
    public Int32 MemberCount { get; set; }
    public IEnumerable<OrganisationalUnitWithParticipantGroups> OrganisationalUnits { get; set; }
}

public class OrganisationalUnitWithParticipantGroups /*: OrganisationalUnit*/ {
    public Guid Id { get; set; }
    public String Name { get; set; }
    public Int32 MemberCount { get; set; }
    public IEnumerable<ParticipantGroup> ParticipantGroups { get; set; }
}

public class ParticipantGroup {
    public Guid Id { get; set; }
    public String Name { get; set; }
    public Int32 MemberCount { get; set; }
}

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多