WCF Web服务返回json格式数据 [英] WCF web service returning json format data
问题描述
我创建了一个返回json格式数据的WCF Web服务.我的代码如下:
I have created a WCF webservice returning json format data. My code is like below:
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<string, string> dict = new Dictionary<string, string>();
foreach (DataRow rs in dt.Rows)
{
dict = new Dictionary<string, string>();
foreach (DataColumn col in dt.Columns)
{
dict.Add(col.ColumnName, rs[col].ToString());
}
}
return (new JavaScriptSerializer().Serialize(dict));
我得到以下输出:
{"SampleServiceResult": "{\" Id \:\" 1 \,\"名称\:\" xyz \,\"电子邮件\:\" xya@test.com \}"}
{ "SampleServiceResult": "{\"Id\":\"1\",\"Name\":\"xyz\",\"email\":\"xya@test.com\"}" }
但是我想要的输出如下:
But I want the output as below:
{"SampleServiceResult": {"Id":"1",名称":"xyz",电子邮件":"xya@test.com"}}
{ "SampleServiceResult": {"Id":"1","Name":"xyz","email":"xya@test.com"} }
在输出中添加"\"转义字符.如何删除它并返回有效的json?
In the output it adds "\" escape character. How can I remove this and return valid json?
我试图替换"\",但是它不起作用.
I have tried to replace "\" but it doesn't work.
谢谢
推荐答案
通过在代码中进行以下更改,我得到了预期的结果:
I have got the expected out by applying following changes in my code:
- 将返回类型从字符串更改为流
-
替换了下面的代码
- Changed return type from String to Stream
Replaced the below code
return (new JavaScriptSerializer().Serialize(dict));
使用
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(sData));
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(sData));
感谢大家的帮助和支持.愿它会帮助某人.
Thanks everybody for help and support. May it will help someone.
这篇关于WCF Web服务返回json格式数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!