Restful服务从数据库获取数据并返回到json

时间:2015-03-12 06:52:09

标签: json rest

我正在创建一个从数据库获取数据并返回到json格式的休息服务。但是在我被困的一个地方。现在我从数据库中获取数据但我不知道如何将该数据转换为json。那么你现在能帮我做下一步的事吗

IWcfDataService.cs

namespace RestWCFService
{

    [ServiceContract]
    public interface IWcfDataService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
         ResponseFormat = WebMessageFormat.Json,
         BodyStyle = WebMessageBodyStyle.Wrapped,
         UriTemplate = "Search/{keyword}")]
        Detail Search(string keyword);
    }

    [DataContract]
    public class Detail
    {

        [DataMember]
        public string student_id { get; set; }

        [DataMember]
        public string First_Name { get; set; }

        [DataMember]
        public string Last_Name { get; set; }


    } 
}

WcfDataService.svc

namespace RestWCFService
{

    public class WcfDataService : IWcfDataService
    {

        public Detail Search(string keyword)
        {



               var json = "";
                var data = "";


                 SqlConnection sql_Search;


                 sql_Search = new SqlConnection("Data Source=FPBLWD0309;Initial Catalog=student_info;Integrated Security=True");
                 sql_Search.Open();

                 SqlCommand SelectCommand = new SqlCommand("SELECT Student_ID,First_Name,Last_Name FROM record Where (First_Name Like '%" + keyword + "%')", sql_Search);


                 SelectCommand.ExecuteNonQuery();
                 SqlDataAdapter SQLAd = new SqlDataAdapter(SelectCommand);
                 SqlDataReader read = SelectCommand.ExecuteReader();

                 while (read.Read())
                 {
                     var De = new Detail { 
                       student_id = read["student_ID"].ToString(),
                       First_Name = read["First_Name"].ToString(),
                       Last_Name  = read["Last_Name"].ToString()
                    };

                 }


           return De;

        }

    }
}

0 个答案:

没有答案