将每行的数据表转换为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");
}
结果Json字符串是:
{"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}
答案 0 :(得分:0)
试试这个:
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];
}
答案 1 :(得分:0)
// 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);
}
}
}