我是C#中Web服务的初学者,用于生成数据JSON。 所以,我有Web服务来抛出格式为JSON的数据, 这是我的结果JSON:
[{"RESULT":"2","TKN":"E952B4C5FA9","URL_HOME":"My_Url_Home"}]
如何在我的结果Json中删除符号“[”和“]”,所以我希望我的结果JSON成为:
{"RESULT":"2","TKN":"E952B4C5FA9","URL_HOME":"My_Url_Home"}
这是我的代码:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void Create_JSON()
{
SqlConnection con = new SqlConnection(consString);
SqlCommand cmd = new SqlCommand();
DataTable dt;
SqlDataReader reader;
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
String resultJSON = "";
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "My_Store_Procedure";
cmd.Connection = con;
con.Open();
reader = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(reader);
con.Close();
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<String, Object>> tableRows = 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].ToString());
}
tableRows.Add(row);
}
resultJSON = serializer.Serialize(tableRows).ToString();
}
catch (Exception ex)
{
resultJSON = ex.Message.ToString();
}
Context.Response.Write(resultJSON);
}
请帮助,并感谢所有答案。
答案 0 :(得分:1)
应该这样吗?
resultJSON = serializer.Serialize(tableRows[0]).ToString();
问题是你的tableRows类型是List,但你希望它是一个对象。
答案 1 :(得分:0)
我不知道你为什么要删除“[”和“]”,因为[]是JSON所必需的。
如果你必须删除[],那么试试这个
resultJSON = serializer.Serialize(tableRows).ToString();
resultJSON = resultJSON.Substring(1, resultJSON.Length - 2);