2012-07-05 61 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