【问题标题】:C# WebApi POST creating a objects with complex json dataC# WebApi POST 创建具有复杂 json 数据的对象
【发布时间】:2020-07-09 22:07:33
【问题描述】:

我有两个模型,一个 SettingCollection 和一个 SettingValue。 SettingCollection 有许多 SettingValue。这就是这种关系的建立。

public class SettingCollection
{
    public int SettingCollectionId { get; set; }
    public string Name { get; set; }
    public string Key { get; set; }
    public int Priority { get; set; }

    public ICollection<SettingValue> SettingValues {get; set; }
}

    public class SettingValue
{
    public int SettingValueId { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
        
    public int SettingCollectionId { get; set; }
    public SettingCollection SettingCollection { get; set; }

}

要在一次调用中创建新的 SettingCollection 和 SettingValues,我将发布以下有效负载:

    {
  "Name": "Company Collection",
  "Key": "company_collection",
  "Priority": 3,
    "SettingValues": 
    [{"Name": "Is this true", "Value": "True"}]
}

我的回答是:

    System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerCycleDetected(Int32 maxDepth)

这只是我不能做的事情,必须使用 NewtonSoft 来提取控制器中的原始数据吗?

谢谢!

【问题讨论】:

    标签: c# entity-framework-core asp.net-core-webapi


    【解决方案1】:

    将此选项添加到您的启动文件中的 newtonsoft.json

      AddNewtonsoftJson(options =>
                    {
                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                        options.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
                    })
    

    【讨论】:

    • 我已经尝试了一些不同的迭代,但我不断收到 AddNewtonsoftJson 的未解析符号。
    • 确保从 nuget 包管理器添加包 Microsoft.AspNetCore.Mvc.NewtonsoftJson。尝试版本 3.1.4
    • 我安装了 3.1.5。
    • 提供更多信息,添加 nuget 包后您的代码是否无法编译。你得到什么错误信息。未解析的符号非常模糊
    【解决方案2】:

    这些类是自引用的,所以它们进入循环。您可以忽略带有JsonIgnoreAttribute 的子类。我将它与System.Text.Json.JsonSerializer 一起使用并且工作正常。

    public class SettingValue
    {
       public int SettingValueId { get; set; }
       public string Name { get; set; }
       public string Value { get; set; }
       public int SettingCollectionId { get; set; }
       
       [JsonIgnore]
       public SettingCollection SettingCollection { get; set; }
    
    }
    

    【讨论】:

    • 就是这样做的。我添加了该连接,因为这是在文档中。 docs.microsoft.com/en-us/ef/core/modeling/…
    • 我认为您可以创建这些类的数据传输对象。它们只是无法序列化,因为它们是自引用的。
    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多