代码改变世界

数据转json数据

2010-01-22 19:17  三皮开发时  阅读(409)  评论(0编辑  收藏  举报

1.GetJson公共类 :将new DataSet().Talbe[0] 转Json 数据 格式 

{ users:[{"name":"zhangsan","age":12},{"name":"lisi","age":13}] };  

可以得出表名为:users

两行两列数据          name    age

                        zhangsan     12

                            lisi            13

另外需要个引用:Newtonsoft.Json.dll         csdn上好多~

---------------------------------------------------------------------------------------------------------

GetJson.cs

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public class Handler : IHttpHandler {
    string resultType;
    DataSet ds;
    string str = ConfigurationManager.AppSettings["ConnectionString"];
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
//        string json http://blog.163.com/=@%22%7B'users':[%7B'name':'zhangshan','age':12}
//            ,{'name':'lisi','age':13}]}";
//        context.Response.Write(json);
//        context.Response.Flush();
//        context.Response.End();
        resultType = "json";//HttpContext.Current.Request["resultType"].ToString();
        if (resultType == "json")
        {
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from tb_Vote", con);
            SqlDataAdapter adapt = new SqlDataAdapter(cmd);
            ds = new DataSet();
            adapt.Fill(ds);
            con.Close();
            if (ds != null)
            {
                context.Response.Write(GetJson.DataTableToJSON(ds.Tables[0], "Fjson"));
            }
           
        }

       
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

----------------------------------------------------------------------------------------------------

Default.aspx.cs

    //方法一 这页面是aspx.cs页面

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    string html;
    DataSet ds;
    string str = ConfigurationManager.AppSettings["ConnectionString"];
    string resultType = "json";//HttpContext.Current.Request["resultType"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
            Response.Write(GetJson.DataTableToJSON(ds.Tables[0], "asdf"));
           
        }

        html = GetResult(resultType);

//以下代码必写 否则在其他页面引用json数据时会传那些  <head><body></body></head>这些东西 使Json数据失效

        Response.Clear();
        Response.Write(html);
        Response.End();


    }
    public void Bind()
    {
        SqlConnection con = new SqlConnection(str);
        SqlCommand cmd = new SqlCommand("select * from tb_Vote", con);
        SqlDataAdapter adapt = new SqlDataAdapter(cmd);
       ds = new DataSet();
        adapt.Fill(ds);
    }

    private string GetResult(string resultType)
    {
        if (resultType == "json")
        {
            return GetJson.DataTableToJSON(ds.Tables[0], "Fson");
        }
        else
        {
            return "你没获取到JSON数据";
        }
    }


}

--------------------------------------------------------------------------------------------------------------------------

//方法二:New 一个      一般处理程序     .ashx

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public class Handler : IHttpHandler {
    string resultType;
    DataSet ds;
    string str = ConfigurationManager.AppSettings["ConnectionString"];
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
//        string json http://blog.163.com/=@%22%7B'users':[%7B'name':'zhangshan','age':12}
//            ,{'name':'lisi','age':13}]}";
//        context.Response.Write(json);
//        context.Response.Flush();
//        context.Response.End();
        resultType = "json";//HttpContext.Current.Request["resultType"].ToString();
        if (resultType == "json")
        {
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from tb_Vote", con);
            SqlDataAdapter adapt = new SqlDataAdapter(cmd);
            ds = new DataSet();
            adapt.Fill(ds);
            con.Close();
            if (ds != null)
            {

               //同样写在页面上       这种类似页面可以算是一个JSON  数据集合 用判断条件控制传入的json数据
                context.Response.Write(GetJson.DataTableToJSON(ds.Tables[0], "Fjson"));
            }
           
        }

       
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

----------------------------------------------------------------------------------------------------------------------------------------------

Default2.asxp   调用Json

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
       
    .L01 td
    {
       width:200px;
       height:20px;
       text-align:left;
       border:solid 1px blue;
       color:Green;
    }
   
    </style>

    <script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#btnAjaxGetJSON").click(function(event) {
                $.getJSON("Default.aspx", { "resultType": "json" }, function(data, textStatus) {
                    //alert("数组长度:" + data.length);
                    var html = "";
                    var h = "<table class='L01'>";
                    $(data["Fson"]).each(function(i, user) {//each就像foreach循环 i 代表的是循环次数
                        //alert(user.name);

                        h += "<tr><td>voteID:" + user.voteID + "</td><td>voteTitle:" + user.voteTitle + "</td></tr>"

                    });
                    h += "</table>";
                   
                    $("div[id=divResult]").html(h);
                    $("#txt1").attr({ "value": data["Fson"][1].voteTitle });
                });
            });
        })
   
    </script>
</head>
<body>
    <button id="btnAjaxGetJSON">getJSON</button><br />
    <br />
 
    <div id="divResult"></div>
    <input type="text" id="txt1" />
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------------------------

over~.