客户端用一个html页面调用一个ashx文件(一般http处理程序),返回json格式的自定义对象: html:-------------------------------------------------- 姓名: 年龄: -------------------------------------------------- handler.ashx文件:-------------------------------------------------------- using System; using System.Web; using System.Runtime.Serialization.Json; using System.Collections; using System.Runtime.Serialization;
public class Handler : IHttpHandler {
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string name = context.Request.Params["name"].ToString(); string age = context.Request.Params["age"].ToString(); person p1 = new person(name,age); DataContractJsonSerializer djson = new DataContractJsonSerializer(p1.GetType()); //将对象序列化为 JavaScript 对象表示法 (JSON) djson.WriteObject(context.Response.OutputStream, p1); } public bool IsReusable { get { return false; } } [DataContract]//要序列化,一定要加这个属性 public class person { [DataMember] //属性“DataMember”只在“property, indexer, field”声明中有效。 public string Name="无名士"; [DataMember] public string Age="0"; public override string ToString() { return "姓名:" + Name + "年龄:" + Age; } public person(string name,string age) //自定义类
person { this.Name = name; this.Age = age; } public person() { } } }
|
请发表评论