zoukankan      html  css  js  c++  java
  • 用json格式返回自定义对象。(jQuery asp.net)

    客户端用一个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() { } } }


  • 相关阅读:
    HTML标签
    Web标准
    Web服务器 (获取域名)
    网站favicon.ico 图标
    模块化
    外边距
    h5css产品模块设计
    用策略模式(自定义注解+包扫描)解决if else 太多的问题
    方法区 永久代 元空间 常量池
    javac jar java
  • 原文地址:https://www.cnblogs.com/mahaisong/p/1966692.html
Copyright © 2011-2022 走看看