【问题标题】:JSON serialization with a circular reference detected检测到循环引用的 JSON 序列化
【发布时间】:2017-02-18 12:05:26
【问题描述】:

我创建了两个类“Candidat”和“Experience”。候选人可能有很多经验

public class Consultant
{
    public int ConsultantID { get; set; }
    public string ConsultantNom { get; set; }
    public string ConsultantPrenom { get; set; }
    public string ConsultantTitre { get; set; }
    public Disponibilite ConsultantDisponibilite { get; set; }
    public virtual ICollection<Experience> Experiences { get; set; }

}

public class Experience
{
    public int ExperienceID { get; set; }
    public virtual Consultant Consultant { get; set; }
    public int ConsultantID { get; set; }
    public string ExperienceNomSociete { get; set; }
    public string ExperiencePoste { get; set; }
    public DateTime ExperienceDebut { get; set; }
    public DateTime ExperienceFin { get; set; }
    public string ExperienceCompetences { get; set; }

在我的控制器中搜索所有候选人时,我编写了这段代码

public JsonResult ConsultantsList()
    {

        var consultants = from c in _consultantRepository.getConsultants()
                          select c;

        return Json(consultants, JsonRequestBehavior.AllowGet);
    }

问题是,当我设置断点时,我收到了结果,但在我的页面中出现了“在序列化类型对象时检测到循环引用”的问题。

这就是我使用 JQuery 解析数据的方式:

 function PopulateConsultantList() {
        $.ajax({
            type: "GET",
            url: "/Consultants/ConsultantsList",
            success: function (data) {
                console.log(data);
                var json = $.parseJSON(JSON.stringify(data));
                console.log(json);
                var corpsTR = '';
                $.each(json, function (i, item) {
                    corpsTR += '<tr><td>' + item.ConsultantPrenom + " " + item.ConsultantNom + '</td>'
                        + '<td>' + item.ConsultantTitre + '</td>'
                        + '<td>Immédiate</td>'
                        + '<td><a href="/Consultants/Details/' + item.ConsultantID + '" class="btn btn-default btn-icon"><i class="fa fa-file-text-o"></i></a>&nbsp;<a href="/Consultants/Delete/' + item.ConsultantID + '"  class="btn btn-danger btn-icon"><i class="fa fa-trash-o"></i></a></td></tr>';
                });
                $("tbody").append(corpsTR);
            }
        });
    }

PS:当Experiences为空时,没有问题。 谢谢

【问题讨论】:

  • 您只需要 4 个属性,因此创建一个仅包含这 4 个属性的匿名对象集合(即使不使用,也没有必要将所有额外数据发送给客户端)

标签: c# jquery json asp.net-mvc-5 entity-framework-6


【解决方案1】:

从 Experience 中移除 Consultant 属性,或向其添加 JsonIgnore 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多