WCF Web服务返回json格式数据
我创建了一个返回json格式数据的WCF Web服务。 我的代码如下:
String sJSONdata = ""; StreamReader reader = new StreamReader(data); sJSONdata = reader.ReadToEnd(); //'now convert the JSON into a data table DataTable dt = GetJSONTable(sJSONdata); dt.TableName = "Customer"; Dictionary dict = new Dictionary(); foreach (DataRow rs in dt.Rows) { dict = new Dictionary(); foreach (DataColumn col in dt.Columns) { dict.Add(col.ColumnName, rs[col].ToString()); } } return (new JavaScriptSerializer().Serialize(dict));
我得到以下输出:
{“SampleServiceResult”:“{\”Id \“:\”1 \“,\”Name \“:\”xyz \“,\”email \“:\”xya@test.com \“}”}
但我想要输出如下:
{“SampleServiceResult”:{“Id”:“1”,“Name”:“xyz”,“email”:“xya@test.com”}}
在输出中它添加“\”转义字符。 如何删除它并返回有效的json?
我试图替换“\”但它不起作用。
谢谢
通过在我的代码中应用以下更改,我得到了预期的结果:
- 将返回类型从String更改为Stream
-
替换下面的代码
return (new JavaScriptSerializer().Serialize(dict));
同
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"; return new MemoryStream(Encoding.UTF8.GetBytes(sData));
感谢大家的帮助和支持。 愿它能帮助别人。
最好让WCF处理序列化,而不是自己做。
您可以使用WebGet属性并指定操作合同的响应格式。
另外,正如评论中指出的那样,您可以返回自己的.NET类而不是Dictionary。
运营合同可能与此类似:
[OperationContract] [WebGet(UriTemplate = "/GetCustomer", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] Customer GetCustomer();
与以下数据合同:
[DataContract] public class Customer { [DataMember] public string Id { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string Email { get; set; } }
然后,您可以使用与此类似的代码实现操作合同:
public Customer GetCustomer() { Customer customer = GetCustomerData(); //Get the data and return a customer object return customer; }