2012-07-05 57 views
1
格式化字符串

有类似这样的问题,但他们参与返回被自动解析到JSON对象。返回一个已经JSON从WCF

我有一个字符串,它包含JSON格式的数据,我只想从我的WCF Web服务返回,以便我可以在Ajax中读取它。

它不工作通过简单地返回字符串(我从ajax得到解析器错误)。我想知道是否有特定的方式,我应该从Web服务返回我的JSON字符串?

我的阿贾克斯是好的,因为我与其他外部JSON提供Web服务测试,但它不符合我自己的(所以我假定这是我返回数据)工作。

仅供参考,这里的获得和JSON的返回的重要组成部分:

WebResponse wr = myReq.GetResponse(); 
Stream receiveStream = wr.GetResponseStream(); 
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8); 
return reader.ReadToEnd(); 

和接口声明:

[OperationContract] 
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
string DoWork(); 

谢谢您的时间。

+0

您可以使用DataContractJsonSerializer将json字符串反序列化为一个对象并从服务中返回对象?这可能是序列化和反序列化的开销。你也可以像使用responseFormat那样返回json字符串作为xml,然后通过提取你的json字符串在你的客户端处理它。 – Rajesh 2012-07-05 10:36:43

回答

7

如果您不希望WCF在响应中使用任何格式(即不将其转换为字符串,这是您当前拥有的字符串),则可以从该操作返回Stream。这样WCF将按原样返回流中的字节(请参见下面的示例代码)。你可以在这篇文章中阅读关于WCF "Raw" Programming Model的更多信息。

public class StackOverflow_11342272 
{ 
    [ServiceContract] 
    public class Service 
    { 
     [OperationContract] 
     [WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
     public Stream DoWork() 
     { 
      string json = "{\"name\":\"John Doe\",\"age\":33,\"married\":true}"; 
      WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"; 
      MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); 
      return ms; 
     } 
    } 
    public static void Test() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     WebClient c = new WebClient(); 
     Console.WriteLine(c.DownloadString(baseAddress + "/DoWork")); 

     Console.Write("Press ENTER to close the host"); 
     Console.ReadLine(); 
     host.Close(); 
    } 
} 
+0

我最初试过这个,但是我得到了同样的错误'GET localhost:15574/MyService.svc/DoWork?callback = jQuery17107469671934377402_1341499510267&_ = 1341499510274 400(Bad Request)' – ThePower 2012-07-05 14:37:49

+0

您需要启用跟踪来查看服务为什么要考虑要求不好。 – carlosfigueira 2012-07-05 14:45:31

+0

另一件事:你正在做一个JSONP调用(而不是“常规” AJAX调用),这意味着需要应对的函数调用进行包装(如:'jQuery17107 ...({“名”:“约翰母鹿” ...);')。当使用原始模式可以控制的响应看起来完全像什么,所以你需要做包装你的代码。 – carlosfigueira 2012-07-05 14:46:54