2012-02-15 19 views
3

我使用簡單的Web服務「的.asmx」。在我的web服務返回的一些數據,如:web服務返回JSON數據,但有XML頭怎麼才能去除

<?xml version="1.0" encoding="utf-8" ?> 
    <string xmlns="http://tempuri.org/"> 

{"Table":[{"minlatency":16.0,"Time":"\/Date(1328248782660+0530)\/"},{"minlatency":7.0,"Time":"\/Date(1328248784677+0530)\/"},{"minlatency":13.0,"Time":"\/Date(1328248786690+0530)\/"},{"minlatency":6.0,"Time":"\/Date(1328248788690+0530)\/"},{"minlatency":20.0,"Time":"\/Date(1328248790707+0530)\/"}]}</string> 

我使用:

[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)] 

[webmethod]在我的服務中,並且它在ajax callback給出錯誤,我希望以json格式返回值。

+0

您可以包含實際方法的代碼嗎? – dillenmeister 2012-02-15 05:56:22

+0

從技術上講,*是* XML,它恰好包含JSON。 – 2016-06-09 20:14:44

回答

1

我有同樣的問題在幾個星期前,我發現,使用以下爲我服務

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public void GetPointers() { 
    DataTable dtmkrs = new DataTable(); 
    dtmkrs.Load(SPs.GetPointers().GetReader()); 

    string[][] pointerArray = new string[dtmkrs.Rows.Count][]; 
    int i = 0; 
    foreach (DataRow mkrs in dtmkrs.Rows) 
    { 
     pointerArray[i] = new string[] { mkrs["LocationID"].ToString(), mkrs["Title"].ToString(), mkrs["Blurb"].ToString(), mkrs["Url"].ToString(), mkrs["LongLatPoint"].ToString() }; 
     i++; 
    } 

    JavaScriptSerializer js = new JavaScriptSerializer(); 
    string strJSON = js.Serialize(pointerArray); 
    dtmkrs.Dispose(); 
    Context.Response.Clear(); 
    Context.Response.ContentType = "application/json"; 
    Context.Response.Flush(); 
    Context.Response.Write(strJSON); 
} 

和下面的JavaScript(使用mootools的)

new Request.JSON({ 
url:<url to webservice>, 
method: 'GET', 
onSuccess: function(resJson, respText) { 
     jsonResponse = resJson; 
    dropJSON(); 
} 
}).send(); 

以前是一個函數用於從ASP.NET中的SQL服務器數據庫獲取Google地圖標記c#

+0

可能不是最優雅的做法,但它是一種功能性的做法。 – kolin 2012-02-15 09:03:22

+0

給出錯誤「服務器在發送HTTP頭之後無法清除頭文件」。 – user1208909 2012-02-15 09:21:11

0

我有一個服務返回JSON,我從jQuery調用,它只返回純JSON。這是我如何定義界面:

<OperationContract()> 
<WebInvoke(Method:="POST", BodyStyle:=WebMessageBodyStyle.Wrapped, ResponseFormat:=WebMessageFormat.Json)> 
Function GetNotes() As List(Of MyClassObject) 
0

您可以使用[Ira Rainy]建議的方法修復它,或者使用屬性來完成相同的工作。使用屬性

,只需把上述所需的方法(S)以下行:

[WebInvokeAttribute(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] 
public string DoSomething() 
{ 
    // your code here 
} 

希望這將解決您的問題。

相關問題