0

我需要以 JSON 格式返回从 MS SQL 2008 表中选择的名称和电子邮件。这是我到目前为止所得到的:

public class RaumHelper
{
    internal static string[] Raum()
    {
        List<string> raumObject = new List<string>();

        using (SqlConnection con = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
        using (SqlCommand cmd = new SqlCommand(@"SELECT NAME, EMAIL FROM RAUM", con))
        {
            con.Open();
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    if (rdr["NAME"] != DBNull.Value && rdr["EMAIL"] != DBNull.Value)
                    {
                        raumObject.Add(rdr["NAME"].ToString());
                        raumObject.Add(rdr["EMAIL"].ToString());
                    }
                }
            }
        }
        return raumObject.ToArray();
    }
}

我想以 json 格式而不是数组返回它。

它应该看起来像这样或类似的:

 {"d":[{
  "Name": "Hans",
  "Email": "bla@blub.de"
  }]}
4

2 回答 2

4

您的 JavaScriptSerializer 类将列表对象转换为 json 格式

string JSonString = new JavaScriptSerializer().Serialize(raumObject).ToString()
于 2012-06-05T12:18:50.000 回答
2

使用JavascriptSerializer Serialize 函数或其他序列化程序,如Json.NET

编辑:

JavascriptSerializer

new JavascriptSerializer().Serialize(new{d=raumObject.ToArray()});

编辑2:

要为您的值设置键,请不要将您的值存储在列表中:

internal static string[] Raum()
{
    List<object> raumObject = new List<object>();

    using (SqlConnection con = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=BOOK-IT-V2;Integrated Security=true;"))
    using (SqlCommand cmd = new SqlCommand(@"SELECT NAME, EMAIL FROM RAUM", con))
    {
        con.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                if (rdr["NAME"] != DBNull.Value && rdr["EMAIL"] != DBNull.Value)
                {
                    raumObject.Add(new{
                         Name=rdr["NAME"].ToString(),
                         Email=rdr["EMAIL"].ToString()
                    });
                }
            }
        }
    }

    return  new JavaScriptSerializer().Serialize(new{d=raumObject.ToArray()});
}
于 2012-06-05T12:19:17.577 回答