序列化“System.Reflection.RuntimeModule”类型的对象时检测到循环引用

时间:2015-06-06 15:24:34

标签: c# jquery json asp.net-mvc

下面的代码将读取oracle表并将json结果返回给视图。 数据已成功加载到datalist中,但视图引发了以下错误:

  

序列化时检测到循环引用   “System.Reflection.RuntimeModule”类型的对象。

Q1:我可以做些什么来修复错误?我已经为我需要检索的数据定义了一个模型(参见下面的模型定义)

Q2:上述方法是读取数据库并返回json的最佳做法吗?

public JsonResult StudList()
{
    string SQL = "select id, name, div_code, block, from students where ....."; //see the below model 
    var con = DB.GetConnection();
    con.Open();
    OracleDataAdapter oraAdapt = new OracleDataAdapter(SQL, con);
    DataTable dt = new DataTable();
    oraAdapt.Fill(dt);
    con.Close();
    con.Dispose();
    List<DataRow> dtList = dt.AsEnumerable().ToList(); 
    return Json(dtList, JsonRequestBehavior.AllowGet); 
}

型号:

public class GetSDetailsModel
{
    public List<GetStudentSearchModel> GetStudentSearchModel { get; set; }
}


public class GetStudentSearchModel
{
    public string id { get; set; }
    public string name { get; set; }
    public string div_code { get; set; }
    public string level_code { get; set; }
    public string program_code { get; set; }
    public string major_code { get; set; }
    public string PGPA { get; set; }     

}

2 个答案:

答案 0 :(得分:3)

List<Dictionary<string, object>> arrResponse = new List<Dictionary<string, object>>();
DataTable reader = db.executeQueryDataTable(sSQL);
foreach (DataRow row in reader.Rows)
{
    Dictionary<string, object> dictRow = new Dictionary<string, object>();
    foreach(DataColumn col in reader.Columns)
        dictRow[col.ColumnName] = row[col.ColumnName];
    arrResponse.Add(dictRow);

}

上面的代码将DataTable转换为可序列化的Dictionary列表。只是序列化arrResponse然后

答案 1 :(得分:2)

正如大卫在评论中所说,你需要将DataRow转换为List&lt; GetStudentSearchModel&gt;。您可以使用Linq的Select方法执行此操作,传递从DataRow对象创建GetStudentSearchModel的lambda表达式。代码如下:

public JsonResult StudList()
{
    string SQL = "select id, name, div_code, block, from students where ....."; //see the below model 
    var con = DB.GetConnection();
    con.Open();
    OracleDataAdapter oraAdapt = new OracleDataAdapter(SQL, con);
    DataTable dt = new DataTable();
    oraAdapt.Fill(dt);
    con.Close();
    con.Dispose();
    List<GetStudentSearchModel> dtList = dt.AsEnumerable()
        .Select(row => new GetStudentSearchModel
        {
            id = row["id"],
            name = row["name"],
            div_code = row["div_code"],
            //...
        }).ToList(); 
    return Json(dtList, JsonRequestBehavior.AllowGet); 
}

只需将其余字段添加到初始化程序块。