如何在wcf中返回json格式

时间:2014-11-06 08:41:28

标签: c# json wcf

我是wcf的新手。我开发了wcf restful

iam通过使用以下代码

序列化为json格式来返回字符串
public string ConvertDataTabletoString()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection("Data Source=mar-pc;database=user;User    ID=sa;Password=123123;"))
        {
            using (SqlCommand cmd = new SqlCommand("select title=tname,tid=taddress from userdetails where userid='1'", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                List<Dictionary<string, object>> rows = 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]);
                    }
                    rows.Add(row);
                }
                return serializer.Serialize(rows);
            }
        }
    }

我将结果作为

“[{\” 标题\ “:\” Sathyam \ “\ ”TID \“:\ ”尼扎马巴德\“}]”

我希望得到结果

{ “标题”: “Sathyam”, “TID”: “尼扎马巴德”}

操作合同和

 [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "MyGetData/{value}/{password}")]

帮助我,我尝试了包裹也没有

的bodystyle

4 个答案:

答案 0 :(得分:0)

由于您序列化了一个词典列表而不是单个对象,因此您有方块。

转义字符的问题可能是双序列化:你已经在转换方法中使用ResponseFormat = WebMessageFormat.Json和序列化字典。 看看这个问题:How do I return clean JSON from a WCF Service?

答案 1 :(得分:0)

是否从WCF服务方法调用ConvertDataTabletoString()方法?如果是,那么您不必手动序列化List<Directory>,因为它是WCF框架作业。

在我看来,你的代码应该是:

public List<Dictionary<string, object>> ConvertDataTabletoString()
{
   // your prev code ...
   return rows;               
}

在WCF服务方法中,您应该返回List<Dictionary<string, object>

答案 2 :(得分:0)

您可以使用以下方法解决问题:

  [ServiceContract]
    public interface IService
    {

 [WebGet(UriTemplate = "GetStates", ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        List<ServiceData> GetStates();
  }

And in Service.cs

        public List<ServiceData> GetStates()
        {
            using (var db = new local_Entities())
            {

                var statesList = db.States.ToList();

                return statesList.Select(state => new ServiceData
                {
                    Id = state.StateId, Value = state.StateName
                }).OrderBy(s => s.Value).ToList();

            }
        }

Note you have to just return the return type collection, at my end I have a List of ServiceData 
  public class ServiceData
    {
        public int Id { get; set; }
        public string Value { get; set; }
    }

答案 3 :(得分:0)

我在这里得到了答案Returning raw json (string) in wcf

将返回类型从字符串更改为流,并在末尾添加此部分

   WebOperationContext.Current.OutgoingResponse.ContentType ="application/json; charset=utf-8";
   return new MemoryStream(Encoding.UTF8.GetBytes(serializer.Serialize(rows)));