关于JSon的示例

来源:互联网 发布:雪梨淘宝网店叫什么 编辑:程序博客网 时间:2024/05/19 16:48

Json,是一种轻量级的数据交换格式 。

 示例:通过Ajax请求取出员工基本信息;

第一步:新建一个Person类

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace AjaxDemo{    public class Person    {        public string Name { get; set; }        public string Age { get; set; }        public string Gender { get; set; }        public string Email { get; set; }        public string Address { get; set; }    }}


第二步:添加JSonOutput.ashx 一般处理程序,把Person对象以json数组输出。

一般处理程序方法体:

 //定义Person对象的数组 List<Person> perList = new List<Person>(); perList.Add(new Person() { Name = "橙子", Age = "18", Gender = "M", Email = "Orange@163.com", Address = "上海" }); perList.Add(new Person() { Name = "苹果", Age = "17", Gender = "F", Email = "Apple@163.com", Address = "北京" }); perList.Add(new Person() { Name = "椰子", Age = "20", Gender = "F", Email = "CocoNut@163.com", Address = "广州" });   //以Json格式字符串把 perList进行输出   //------1,初始化一个JavaScriptSerializer对象   JavaScriptSerializer jss = new JavaScriptSerializer();   //------2,获得一个对象的Json格式   string JsonList = jss.Serialize(perList);   context.Response.Write(JsonList);

第三步:在HTML页面中读取返回的JSon数组

<head>    <script src="js/ajax.js"></script>    <script type="text/javascript">        function readjsonlist() {            ajax("JsonOutput.ashx", function (result) {                var pers = JSON.parse(result);                for (var i = 0; i < pers.length; i++) {                    var p = pers[i];                    alert("姓名:" + p.Name + "年龄:" + p.Age);                }            });        }    </script></head><body>    <input type="button" onclick="readjsonlist()" value="点击查看数组对象" /></body>




0 0
原创粉丝点击