WebService返回json格式数据供苹果或者安卓程序调用

本文介绍了一个简单的WebService示例,该服务能够返回JSON格式的数据。通过.NET Framework实现,并使用JavaScriptSerializer进行序列化。

1.新建一个WebService.

2.

 1     /// <summary>
 2     /// DemoToJson 的摘要说明
 3     /// </summary>
 4     [WebService(Namespace = "http://tempuri.org/",Description=("<br><p >西安xx公司</p>技术支持:王光旭"))]
 5     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 6     [System.ComponentModel.ToolboxItem(false)]
 7     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
 8     [System.Web.Script.Services.ScriptService]
 9     public class DemoToJson : System.Web.Services.WebService
10     {
11         /// <summary>
12         /// 这是一个测试WebService返回json格式数据方法
13         /// </summary>
14         /// <returns></returns>
15         [WebMethod(Description = "这是一个测试WebService返回json格式数据方法")]
16         [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
17         //[ScriptMethod]
18         public void HelloWorld()
19         {
20             Context.Response.Clear();
21             Context.Response.ContentType = "application/json";
22             JavaScriptSerializer json = new JavaScriptSerializer();
23             var list = new List<TempJson>()
24             {
25                 new TempJson(){Id=1,Name="张三",Age=25,Sex=""},
26                 new TempJson(){Id=1,Name="李四",Age=1,Sex=""},
27                 new TempJson(){Id=1,Name="王五",Age=2,Sex=""},
28                 new TempJson(){Id=1,Name="赵六",Age=55,Sex=""},
29                 new TempJson(){Id=1,Name="孙八",Age=90,Sex=""}
30             };
31 
32             var jsonList = new { result = "返回成功", Count = list.Count, list };
33 
34             string resultStr = json.Serialize(jsonList);
35             Context.Response.Write(resultStr);
36             Context.Response.End();
37         }
38     }
39 
40     [Serializable]
41     public class TempJson
42     {
43         public int Id { get; set; }
44         public string Name { get; set; }
45         public int Age { get; set; }
46         public string Sex { get; set; }
47     }

3.运行后结果:

4.当刷新当前地址的时候就会报错如下所示:

解决办法:

测试中没加的时候苹果开发调用返回的json数据后面会带着xml的一些信息,加了之后解析正常。

 

转载于:https://www.cnblogs.com/wgx0428/p/4414858.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值