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

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的一些信息,加了之后解析正常。

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。