c# - JSON自引用循环

标签 c# asp.net json

我正在构建一些小型预订应用程序,并且一直收到此错误。

我解决了它:
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

但现在我得到这样的答案:

{
    "ApartmentId": 1,
    "Building": {
        "BuildingId": 1,
        "Apartments": [
            {
                "ApartmentId": 2,
            }
        ]
    },
}

对于类(class) build ,一切正常。公寓只会“走得很远”。我尝试了该主题的解决方案,但没有奏效:https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type#=

这是我的类(class):
public class Apartment
{
    public int ApartmentId { get; set; }
    public Building Building { get; set; }
}

public class Building
{
    public int BuildingId { get; set; }
    public List<Apartment> Apartments { get; set; }
}

问题是,我错过了什么?如何摆脱公寓二次挂牌?

最佳答案

由于您使用的是 Newtosoft 的 Json 库,因此您可以使用属性 [JsonIgnore] .具有此属性的属性不会显示在您的 json 中。

您可以将其与 Building 类中的 Apartments 属性一起使用:

public class Building
{
    //All other properties ...

    [JsonIgnore]
    public List<Apartment> Apartments { get; set; }
}

如果你想对同一个类有不同的序列化行为,我建议实现 DTO classes approach每个数据传输场景的每个类,并根据需要添加属性。

还有this document来自微软关于 DTO 模式。

关于c# - JSON自引用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829391/

相关文章:

c# - 我可以扩展 LINQ-to-SQL 支持的运算符吗?

c# - IComparable 是在字典中强制使用唯一键的最佳方式吗?

c# - 如今“形状 - 追加”查询等效性

javascript - 来自未发布的 Google Drive 电子表格的 JSON 数据?

java - 使用 jackson 删除 JSON 元素

c# - C# 中的整数范围列表

c# - 如何在 C# 中将列标题添加到 ListView

http-redirect - 发出重定向 (HTTP 302) 以在不使用 Java 脚本的情况下作用于 _top 框架

asp.net - ASP .NET MVC 中的 TinyMCE 拼写检查器

ios - 是否可以使用 Django 评论构建事件源?