簡體   English   中英

Json序列化異常

[英]Json Serialization Exception

模型之間的關系是:X有很多Y; Y有許多Z:

class X 
{
    int Id { get; set; }
    [JsonIgnore]
    IList<Y> Y { get; set; }
}

class Y
{
    int Id { get; set; }
    X x { get; set; }
    [JsonIgnore]
    IList<Z> Z { get; set; }
}

class Z
{
    int Id { get; set; }
    Y y { get; set; }
}

public class YBinder : DefaultModelBinder
{
    readonly IQuizRepository _quizRepository = DependencyResolver.Current.GetService<IQuizRepository>();

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var y = (Y)base.BindModel(controllerContext, bindingContext);
        if (problem.Chapter != null)
        {
            y.X = _quizRepository.getX(y.X.Id);
        }
        return y;
    }
}

public class ZBinder : DefaultModelBinder
{ 
    readonly IQuizRepository _quizRepository = DependencyResolver.Current.GetService<IQuizRepository>();

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var z = (Z)base.BindModel(controllerContext, bindingContext);
        if (z.Y != null)
        {
            z.Y = _quizRepository.getY(z.Y.Id);
        }
        return z;
    }
}

我的問題是,已填充網格X和Y,但網格Z拋出JsonSerializationException 這是填充網格Z並引發異常的操作:

public ContentResult Problems(JqInViewModel jqParams)
{
    var problems = _quizRepository.Problems(jqParams.page - 1, jqParams.rows, jqParams.sidx, jqParams.sord == "asc");

    var totalProblems = _quizRepository.TotalProblems(false);

    return Content(JsonConvert.SerializeObject(new
    {
        page = jqParams.page,
        records = totalProblems,
        rows = problems,
        total = Math.Ceiling(Convert.ToDouble(totalProblems) / jqParams.rows)
    }, new CustomDateTimeConverter()), "application/json");
}

問題在於JSON的存在。 當我將[JsonIgnore]放在類Z中進行調試時,網格將毫無例外地加載,否則它將提供Newtonsoft.Json.JsonSerializationException

class Z
{
    int Id { get; set; }
    [JsonIgnore]          // this removes exception but then I cant bind y in grid
    Y y { get; set; }
}

有人可以幫助我找出問題所在嗎?

您的模型中具有循環依賴項,並且不能僅由於JSON格式不支持JSON就將這些對象圖進行序列化。 您將必須以這種方式重新考慮模型,以便打破循環依賴性。 想一想,傳遞給視圖然后將域模型展平為簡單視圖模型所需的唯一信息是什么。 最后,將此扁平化的視圖模型傳遞給視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM