2016-03-05 49 views
0

只得到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"}] 
+0

不要手動序列化JSON的Web服務。您返回對象本身,並將該服務序列化爲正確的類型。除此之外, - – GSerg

+0

[從.NET服務中使用jQuery獲取JSON數據:與ajax設置混淆](http://stackoverflow.com/questions/5690882/get-json-data-with-jquery-from -a-net-service-confused-with-ajax-setup) – GSerg

+0

@GSerg我在aspx頁面中沒有使用任何'ajax'。此應用程序不包含aspx頁面。我只是創建webservices。 – deepak

回答

0

你應該使用下面,不要手動序列化,只是做了以下

[WebService(Namespace = "http://example.com/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]System.Web.Services.WebService 
[ScriptService] 
public class services :WebService 
{  
    [WebMethod(CacheDuration = 60)] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public List<TestObject> GetObjectCollection() 
    { 
      return YourService.GetObjectCollection().ToList(); 
    } 
} 

Refrences:getting-json-data-using-an-asmx-web-servicehere

+0

這可能仍然[不夠](http://stackoverflow.com/q/5690882/11683)。 – GSerg

+0

是它的工作與[鏈接](http://stackoverflow.com/questions/19563641/how-to-get-json-response-from-a-3-5-asmx-web-service) – deepak

+0

@deepak我有downvoted解決方案,並留下評論爲什麼。 – GSerg