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() { } } }


  • 相关阅读:
    2019.4.1 JMeter中文乱码解决方案
    19.3.25 sql查询语句
    2019.3.23 python的unittest框架与requests
    2019.3.22 JMeter基础操作
    19.3.21 计算机网络基础知识
    19.3.20 cmd操作:1.dir查看当前文件夹内的文件;2.alt+space+c关闭cmd窗口
    19.3.20 解决pycharm快捷键无法使用问题和熟悉git与码云操作流程
    19.3.19 使用Flask框架搭建一个简易登录服务器
    回调函数
    var img = new Image()
  • 原文地址:https://www.cnblogs.com/mahaisong/p/1966692.html
Copyright © 2011-2022 走看看