需要在结果中添加1个单词

时间:2014-04-03 11:38:12

标签: asp.net json web-services

我正在创建一个webservice,它应该从数据库(sql server)获取数据并返回它。 每件事都很好。但我需要的是我需要以我需要的格式显示数据。

这是我的代码:

public string GetEmployees()
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "SELECT *  FROM Contact e ";
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.SelectCommand.Connection = con;
            da.Fill(dt);
            con.Close();

            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row = null;
            foreach (DataRow rs in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, rs[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);
        }     

        public string errmsg(Exception ex)
        {
            return "[['ERROR','" + ex.Message + "']]";
        }

上述代码的结果是:

[{"Id":1,"FirstName":"devi","LastName":"priya","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},
{"Id":3,"FirstName":"karu","LastName":"ronald","Contactno":"8883205008"}]

我需要的只是{“货物”这个词:最后我的结果} 这是我期望的结果

{ "Cargo": [{"Id":1,"FirstName":"devi","LastName":"priya","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},
{"Id":3,"FirstName":"karu","LastName":"ronald","Contactno":"8883205008"}]}

任何人都可以帮我解决这个问题。

提前致谢。

1 个答案:

答案 0 :(得分:2)

而不是return serializer.Serialize(rows);return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";