嗨(我是JSON的新手,这是我的第一个Web服务)
我在asp.net中创建了一个返回JSON数据的Web服务,每件事都可以正常工作,但是我需要的是从数据库中获取数据时,它应该在显示之前修剪空白。
因为在我的数据库中,我已将字段类型指定为nvarchar(100),但插入了<20个字符的文本,所以在输出中,我也获得了带空格的结果,例如:
{"Cargo":[{"Id":1,"FirstName":"devi ","LastName":"priya ","Contactno":"965577796 "}]}
在名称devi和priya之后,如果有空格,则有很多。但是我应该得到的实际结果是:
{"Cargo":[{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "}]}
这是我的代码;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
//public string GetEmployees(string SearchTerm)
public void GetEmployees()
{
try
{
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);
//return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
//JavaScriptSerializer js = new JavaScriptSerializer();
//string strJSON = js.Serialize(new { Cargo = rows });
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
//return serializer.Serialize(new { Cargo = rows });
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
谁能帮帮我吗。
提前致谢。
您好以下代码可帮助我修剪空白:
row.Add(col.ColumnName, rs[col].ToString().Trim());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句