我是 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);
}
;
请帮忙,并感谢所有回答。
应该是这样的吧?
resultJSON = serializer.Serialize(tableRows[0]).ToString();
问题是您的表行类型是列表,但您希望是一个对象。
我不知道
你为什么要删除"["和"]",因为[]对于JSON是必需的。
如果您必须删除 [],请尝试此操作
resultJSON = serializer.Serialize(tableRows).ToString();
resultJSON = resultJSON.Substring(1, resultJSON.Length - 2);