我正在构建一些小型预订应用程序,并且一直收到此错误。
我解决了它:
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/