返回值组合:

json返回

1 StringBuilder sb = new StringBuilder();
2 sb.Append("{");
3 sb.Append("\"Status\":\"" + 123 + "\"");
4 sb.Append("}");

json数组

StringBuilder sb = new StringBuilder();
sb.Append("[");
for (int i = 0; i < 10; i++)
{
     sb.Append("{");
     sb.Append("\"name\":\"" + i + "\",");
     sb.Append("\"name1\":\"" + (i+1) + "\"");
     sb.Append("},");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append("]");

 

案例1:

 1 public void GetClass(string name, string id)
 2         {
 3             try
 4             {
 5                 string connectString = System.Configuration.ConfigurationSettings.AppSettings["connStr"];
 6                 SqlConnection conn = new SqlConnection(connectString);
 7                 conn.Open();
 8                 SqlCommand comm = new SqlCommand();
 9                 comm.Connection = conn;
10                 comm.CommandText = "PROC_ChoicePersonnel";
11                 comm.CommandType = System.Data.CommandType.StoredProcedure;
12                 //传值以及赋值  
13                 SqlParameter[] sps = new SqlParameter[] {
14                     new SqlParameter("@ClassName",name),
15                     new SqlParameter("@id",id),
16                     new SqlParameter("@flag","class")
17                   };
18                 comm.Parameters.AddRange(sps);
19 
20                 SqlDataAdapter sdap = new SqlDataAdapter();
21                 sdap.SelectCommand = comm;
22                 DataTable dt = new DataTable();
23                 sdap.Fill(dt);
24                 conn.Close();
25                 StringBuilder sb = new StringBuilder();
26                 sb.Append("[");
27                 for (int i = 0; i < dt.Rows.Count; i++)
28                 {
29                     sb.Append("{");
30                     sb.Append("\"id\":\"" + dt.Rows[i]["id"].ToString() + "\",");
31                     sb.Append("\"name\":\"" + dt.Rows[i]["name"].ToString() + "\"");
32                     sb.Append("},");
33                 }
34                 sb.Remove(sb.ToString().LastIndexOf(','), 1);
35                 sb.Append("]");
36                 Result(sb);
37             }
38             catch (Exception ex)
39             {
40 
41             }
42         }    
43 
44       private void Result(StringBuilder sb)
45         {
46             Context.Response.Charset = "UTF-8"; //设置字符集类型  
47             Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
48             Context.Response.ContentType = "text/plain";
49             Context.Response.Write(sb.ToString());
50             Context.Response.End();
51         }
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-18
  • 2021-09-26
  • 2021-12-11
  • 2021-10-09
  • 2022-12-23
相关资源
相似解决方案