- 很多时候不同的客户端需要通过json通信,这里就是一个将从数据库查询到的列表转化为json格式的方法
private string GetDatasetToJson(DataSet ds)
{
if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
{
//如果查询到的数据为空则返回标记ok:false
return "{\"ok\":false}"
}
StringBuilder sb = new StringBuilder()
sb.Append("{\"ok\":true,")
foreach (DataTable dt in ds.Tables)
{
sb.Append(string.Format("\"{0}\":[", dt.TableName))
foreach (DataRow dr in dt.Rows)
{
sb.Append("{")
for (int i = 0
{
sb.AppendFormat("\"{0}\":\"{1}\",", dr.Table.Columns[i].ColumnName.Replace("\"", "\\\"").Replace("\'", "\\\'"), ObjToStr(dr[i]).Replace("\"", "\\\"").Replace("\'", "\\\'")).Replace(Convert.ToString((char)13), "\\r\\n").Replace(Convert.ToString((char)10), "\\r\\n")
}
sb.Remove(sb.ToString().LastIndexOf(','), 1)
sb.Append("},")
}
sb.Remove(sb.ToString().LastIndexOf(','), 1)
sb.Append("],")
}
sb.Remove(sb.ToString().LastIndexOf(','), 1)
sb.Append("}")
return sb.ToString()
}
public ActionResult GroupToOpenfire(string username)
{
string jString = "";
if (username != null)
{
jString = GetDatasetToJson(DB.GetDataSet(EnringContext.Current.Config.ConnectionStrings.Server, CommandType.Text, string.Format("select ofMucRoom.name from ofMucRoom where ofMucRoom.roomID in(select ofMucMember.roomID from ofMucMember where jid='{0}')", username)));
}
return Content(jString);
}
public ActionResult GroupMemberToOpenfire(string groupname)
{
string jString = "";
if (groupname != null)
{
jString = GetDatasetToJson(DB.GetDataSet(EnringContext.Current.Config.ConnectionStrings.Server, CommandType.Text, string.Format("select ofMucMember.jid from ofMucMember where ofMucMember.roomID in(select ofMucRoom.roomID from ofMucRoom where name='{0}')", groupname)));
}
return Content(jString);
}