Wcf Web服务返回json格式数据 [英] Wcf web service return json format data
问题描述
您好
我使用c#创建了WCF webservice并返回了json格式数据。我的代码如下:
Hello
I have created WCF webservice using c# and it return json format data. My code is like below:
public string SampleService(Stream data)
{
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 \,\email \:\xya@test.com \}}}
我想要输出如下:
{SampleServiceResult:{Id:1,Name:xyz,email :xya@test.com}}
在输出中,它在输出中添加\转义字符。如何删除它并在输出中返回有效的json。
谢谢
我是什么尝试过:
我试图替换\但它不起作用。
And I get the following output:
{ "SampleServiceResult": "{\"Id\":\"1\",\"Name\":\"xyz\",\"email\":\"xya@test.com\"}" }
I want output as below:
{ "SampleServiceResult": {"Id":"1","Name":"xyz","email":"xya@test.com"} }
In output it add "\" escape character in output. How can I remove this and return valid json in output.
Thanks
What I have tried:
I have tried to replace "\" but it doesn't work.
推荐答案
通过在我的代码中应用以下更改,我得到了预期的结果:
1.将返回类型从String更改为Stream
2.替换代码
Hi,
I have got the expected out by applying following changes in my code:
1. Changed return type from String to Stream
2. Replaced the code
return (new JavaScriptSerializer().Serialize(dict));
with
with
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(sData));
感谢大家的帮助和支持。
谢谢
Rajesh
Thanks everybody for help and support.
Thanks
Rajesh
这篇关于Wcf Web服务返回json格式数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!