2016-03-05 66 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