【问题标题】:Create JsonResult from C# SqlDataReader从 C# SqlDataReader 创建 JsonResult
【发布时间】:2018-04-17 20:17:00
【问题描述】:

我需要将SqlDataReader 序列化为 Json。

我在互联网上研究了一些例子,但是所有结果都是“文本”而不​​是带有线条的对象。

我做错了什么?

我的实现:

public JsonResult Teste()
{
    using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString))
    {
        db.Open();

        using (SqlCommand comando = new SqlCommand("select * from USERS", db))
        {
            using (SqlDataReader reader = comando.ExecuteReader())
            {
                DataTable dataTable = new DataTable();
                dataTable.Load(reader);  

                var resultado = JsonConvert.SerializeObject(dataTable);

                return Json(resultado, JsonRequestBehavior.AllowGet);
            }
        }
    }
}

我的结果:

"[{\"UsuarioID\":1,\"Email\":\"admin\",\"Nome\":\"SISTEMA\"},{\"UsuarioID\":2,\"Email\":\"marlon.tiedt@gmail.com\",\"Nome\":\"Marlon Tiedt\"},{\"UsuarioID\":3,\"Email\":\"marlon.tiedt@megasul.com.br\",\"Nome\":\"Marlon - Megasul\"}]"

期望的结果:

[{"UsuarioID":1,"Email":"admin","Nome":"SISTEMA"},{"UsuarioID":2,"Email":"marlon.tiedt@gmail.com","Nome":"Marlon Tiedt"},{"UsuarioID":3,"Email":"marlon.tiedt@megasul.com.br","Nome":"Marlon - Megasul"}]

【问题讨论】:

  • 到底是什么问题,转义字符?这些只是在调试器中查看它的结果。什么是“有线条的物体”?
  • 我的问题是结果不是对象而是文本。我的结果在 "" 字符之间。这样我就不能在 View 中使用它。 @Plutonix
  • 我还有其他Json,它来自Linq,可以正确生成记录。示例:{"rows":[{"UsuarioVisaoID":2,"Email":"admin","Nome":"SISTEMA","Status":"A","Fixo":"Não"},{"UsuarioVisaoID":5,"Email":"marlon.tiedt@gmail.com","Nome":"Marlon Tiedt","Status":"A","Fixo":"Não"}],"total":2}
  • 对,您正在对 JSON 进行双重序列化,如 JSON.NET Parser seems to be double serializing my objects 所示。所以,不要这样做,直接返回你的对象。

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


【解决方案1】:

您是双重编码输出,只需将 dataTable 对象传递给 new Json(...) ,它应该可以正常工作。见下面修改后的代码

public JsonResult Teste()
{
    using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["Conexao"]     .ConnectionString))
  {
    db.Open();
    using (SqlCommand comando = new SqlCommand("select * from USERS", db))
    {
        using (SqlDataReader reader = comando.ExecuteReader())
        {
            DataTable dataTable = new DataTable();
            dataTable.Load(reader);  
            return Json(dataTable, JsonRequestBehavior.AllowGet);
        }
    }
  }
}

【讨论】:

  • 解决方案无效。生成错误:pastebin.com/mfnQHn9V
  • @MarlonTiedt 这只是一个堆栈跟踪,您忘记告诉我们实际的错误消息。但我怀疑返回整个数据表对象不是一个好主意。创建一个仅包含您需要的实际字段的 DTO 对象,从数据表中读取数据,然后将其作为 JSON 发送回。或者可能正如 dbc 下面所说,您使用的是旧版本的 MVC,并且它使用的 JsonSerializer 类不再使用或微软特别推荐,他们现在将此功能委托给 JSON.NET,因为它更擅长。将您的默认序列化程序切换到该序列化程序也可能会有所帮助。
  • @MarlonTiedt - 看起来您可能使用的是旧版本的 asp.net-mvc,它使用了 JavaScriptSerializer。来自techblog.dorogin.com/…ASP.NET MVC4 自 4.5 RC 现在使用 Newtonsoft.Json (Json.Net);确认here。要在旧版本的 MVC 中使用 Json.NET,请参阅 Setting the default JSON serializer in ASP.NET MVC
【解决方案2】:

Json 在内部序列化您传递给它的任何数据。在您的情况下,您传递的是序列化字符串而不是实际数据,因此它会在响应中添加斜杠。因此,删除序列化并将对象直接传递给 Json,您将获得正确的 json 响应.

【讨论】:

    【解决方案3】:
     -- One Standard way of doing this is convert your datatable into List<Dictionary<string, object>>. Below is the sample code.
    
    
    public JsonResult Teste()
    {
        using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString))
        {
            db.Open();
    
            using (SqlCommand comando = new SqlCommand("select * from USERS", db))
            {
                using (SqlDataReader reader = comando.ExecuteReader())
                {
                    DataTable dataTable = new DataTable();
                    dataTable.Load(reader);  
    
                    var resultado = GetTableRows(dataTable);
    
                    return Json(resultado, JsonRequestBehavior.AllowGet);
                }
            }
        }
    }
    
    
    
    
    
    
    public List<Dictionary<string, object>> GetTableRows(DataTable dtData)
    {
                List<Dictionary<string, object>> 
                lstRows = new List<Dictionary<string, object>>();
                Dictionary<string, object> dictRow = null;
    
                foreach (DataRow dr in dtData.Rows)
                {
                    dictRow = new Dictionary<string, object>();
                    foreach (DataColumn col in dtData.Columns)
                    {
                        dictRow.Add(col.ColumnName, dr[col]);
                    }
                    lstRows.Add(dictRow);
                }
                return lstRows;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-19
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      相关资源
      最近更新 更多