将数据表转换为json时出错

本文关键字:出错 json 数据表 转换 | 更新日期: 2023-09-27 18:08:32

当将每行数据表转换为json时,我没有得到适当的格式,也得到错误"RowError":"","RowState":2

下面是我的代码:
 StrQry="select * from doctor_mas where version_code=1";
        DataTable dt=new DataTable();
        dt=Sqlhelper.OleDbTable(StrQry);

        try
        {
            for(int i=0;i<dt.Rows.Count;i++)
            {
             string JSONresult;
             JSONresult = JsonConvert.SerializeObject(dt.Rows[i]);
             var Update = new Salestrak.Update.updDoc();
             String Authrized = Update.updateTable((int)dt.Rows[i][0], "doctor_mas", JSONresult); 
            }
        }
        catch
        {
            MessageBox.Show("Sync Aborted");
        }

result Json string is:

{"RowError":"","RowState":2,"Table":[{"id":248.0,"birth_date":"1950-01-01T00:00:00","doctor_code":"D248","doctor_name":"Ajay A Haryani","version_code":1},{"id":293.0,"birth_date":"1990-05-26T00:00:00","doctor_code":"D293","doctor_name":"Aarti  Thakker","version_code":1}],"ItemArray":[248.0,"1950-01-01T00:00:00","D248","Ajay A Haryani",0,1.0,2.0,"Sandip Palekar","Mumbai-2",2.0,"Vasudhan,1],"HasErrors":false}

将数据表转换为json时出错

试试这个:

string JSONresult = JsonConvert.SerializeObject(dt.Rows[i].ItemArray);

基本上你想序列化DataRow的内容数组。

有一些开销的替代方案-

var o = JsonConvert.SerializeObject(dt.Rows[0]);
for (var i = 0; i < JObject.Parse(o)["Table"].Count(); i++)
{
    var t = JObject.Parse(o)["Table"][i];
}

From suresh's blog

// This method is used to convert datatable to json string
public string ConvertDataTabletoString()
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true"))
    {
        using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con))
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);
        }
    }
}