如何使用webservice只获取json数据

时间:2016-03-05 06:52:09

标签: c# asp.net json web-services asmx

我创建了网络服务:

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

即使我已经定义了Json响应格式,它的内容类型也是text/xml

我怎样才能获得如下所示的json响应?

[{"Id":1,"Name":"xyz"},{"Id":2,"Name":"abc"}]

1 个答案:

答案 0 :(得分: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();
    }
}

参考:getting-json-data-using-an-asmx-web-servicehere