只得到JSON數據有創建Web服務:我如何與web服務
demo.asmx
<%@ WebService Language="C#" CodeBehind="~/App_Code/demo.cs" Class="demo" %>
demo.cs
public class demo : System.Web.Services.WebService
{
public demo()
{
}
[WebMethod]
[ScriptMethod(UseHttpGet = true, XmlSerializeString = false, ResponseFormat = ResponseFormat.Json)]
public string saveUserData()
{
Employee[] emps = new Employee[] {
new Employee()
{
Id=1,
Name="xyz"
},
new Employee()
{
Id=2,
Name="abc"
}
};
return new JavaScriptSerializer().Serialize(emps);
}
}
現在,當我運行這個那麼它給了我以下數據:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string>[{"Id":1,"Name":"xyz"},{"Id":2,"Name":"abc"}]</string>
所以我有檢查控制檯,它給我的
Cache-Control → private, max-age=0
Content-Encoding → gzip
Content-Length → 232
Content-Type → text/xml; charset=utf-8
Date → Sat, 05 Mar 2016 06:33:53 GMT
Server → Microsoft-IIS/8.0
Vary → Accept-Encoding
X-AspNet-Version → 4.0.30319
X-Powered-By → ASP.NET
X-SourceFiles → =?UTF-8?B?RDpcRGVtb193ZWJz
它給人的內容類型爲text/xml
連我都定義了JSON響應格式。
我怎樣才能得到像下面這樣的json響應?
[{"Id":1,"Name":"xyz"},{"Id":2,"Name":"abc"}]
不要手動序列化JSON的Web服務。您返回對象本身,並將該服務序列化爲正確的類型。除此之外, - – GSerg
[從.NET服務中使用jQuery獲取JSON數據:與ajax設置混淆](http://stackoverflow.com/questions/5690882/get-json-data-with-jquery-from -a-net-service-confused-with-ajax-setup) – GSerg
@GSerg我在aspx頁面中沒有使用任何'ajax'。此應用程序不包含aspx頁面。我只是創建webservices。 – deepak