我如何与web服务
问题描述:
只得到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"}]
答
你应该使用下面,不要手动序列化,只是做了以下
[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-service 或here
不要手动序列化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