23

クラスを与える:

public class Parent
{
    public int id {get; set;}
    public int name {get; set;}

    public virtual ICollection<Child> children {get; set;}
}

[Table("Child")]
public partial class Child
{
    [Key]
    public int id {get; set;}
    public string name { get; set; }

    [NotMapped]
    public string nickName { get; set; }
}

そしてコントローラーコード:

List<Parent> parents = parentRepository.Get();
return Json(parents); 

LOCALHOST では動作しますが、ライブ サーバーでは動作しません。

エラー: Json タイプのオブジェクトをシリアライズ中に循環参照が検出されました

検索して[ScriptIgnore]属性を見つけたので、モデルを次のように変更しました

using System.Web.Script.Serialization;

public class Parent
{
    public int id {get; set;}
    public int name {get; set;}

    [ScriptIgnore]
    public virtual ICollection<Child> children {get; set;}
}

しかし、ライブサーバー(win2008)でも同じエラーが発生します。

そのエラーを回避し、親データを正常にシリアル化するにはどうすればよいですか?

4

4 に答える 4

48

次のコードを試してください。

return Json(
    parents.Select(x => new {
        id = x.id,
        name = x.name,
        children = x.children.Select(y => new {
            // Assigment of child fields
        })
    })); 

...または、親プロパティのみが必要な場合:

return Json(
    parents.Select(x => new {
        id = x.id,
        name = x.name
    })); 

これは実際には問題の解決策ではありませんが、DTO をシリアル化する際の一般的な回避策です...

于 2013-01-29T21:53:13.620 に答える
2

このコードを使用できますが、select Extention 関数を使用して列をフィルター処理することはできません。

var list = JsonConvert.SerializeObject(Yourmodel,
    Formatting.None,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return list;
于 2016-09-18T10:36:31.877 に答える
1

MVC5ビューでKnockoutを使用しているため、修正を使用しています。

行動中

return Json(ModelHelper.GetJsonModel<Core_User>(viewModel));

関数

   public static TEntity GetJsonModel<TEntity>(TEntity Entity) where TEntity : class
    {
        TEntity Entity_ = Activator.CreateInstance(typeof(TEntity)) as TEntity;
        foreach (var item in Entity.GetType().GetProperties())
        {
            if (item.PropertyType.ToString().IndexOf("Generic.ICollection") == -1 && item.PropertyType.ToString().IndexOf("SaymenCore.DAL.") == -1)
                item.SetValue(Entity_, Entity.GetPropValue(item.Name));
        }
        return Entity_;  
    }
于 2014-09-14T12:03:53.043 に答える