JQuery把DataTable、list<>数据转换成JSON数据

 

 代码如下 复制代码

一般处理程序JsonDate.ashx
 
 
public void ProcessRequest(HttpContext context)
   
{
       
context.Response.ContentType =
"text/plain"
;
       
DataTable data2 = myData();
       
string str = DataTableToJson(
"myJson"
, data2);
//构建的json数据
       
context.htm = htm&(str);
   
}
   
public bool IsReusable
   
{
       
get
       
{
           
return
 
false
;
       
}
   
}
   
//用datatable做数据,数据模拟
   
public DataTable myData()
   
{
       
DataTable dt =
new
 
DataTable();
       
DataColumn dc;
       
DataRow dr;
       
dc =
new
 
DataColumn(
"Name"
, System.Type.GetType(
"System.String"
));
       
dt.Columns.Add(dc);
       
dc =
new
 
DataColumn(
"Email"
, System.Type.GetType(
"System.String"
));
       
dt.Columns.Add(dc);
       
dc =
new
 
DataColumn(
"Phon"
, System.Type.GetType(
"System.String"
));
       
dt.Columns.Add(dc);
       
dc =
new
 
DataColumn(
"Move"
, System.Type.GetType(
"System.String"
));
       
dt.Columns.Add(dc);
       
dc =
new
 
DataColumn(
"Pan"
, System.Type.GetType(
"System.String"
));
       
dt.Columns.Add(dc);
       
dc =
new
 
DataColumn(
"select"
, System.Type.GetType(
"System.String"
));
       
dt.Columns.Add(dc);
       
for
 
(int i = 1; i < 7; i++)
       
{
           
dr = dt.NewRow();
           
dr[
"Name"
] =
"Name"
 
+ i.ToString();
           
dr[
"Email"
] =
"Email"
 
+ i.ToString();
           
dr[
"Phon"
] =
"Phon"
 
+ i.ToString();
           
dr[
"Move"
] =
"Move"
 
+ i.ToString();
           
dr[
"Pan"
] =
"Pan"
 
+ i.ToString();
           
dr[
"select"
] = i.ToString();
           
dt.Rows.Add(dr);
       
}
       
int count = dt.Rows.Count;
       
return
 
dt;
   
}
   
//将datatable数据转换成JSON数据
   
public string DataTableToJson(string jsonName, DataTable dt)
   
{
       
StringBuilder Json =
new
 
StringBuilder();
       
Json.Append(
"["
);
       
if
 
(dt.Rows.Count > 0)
       
{
           
for
 
(int i = 0; i < dt.Rows.Count; i++)
           
{
               
Json.Append(
"{"
);
               
for
 
(int j = 0; j < dt.Columns.Count; j++)
               
{
                   
Json.Append(dt.Columns[j].ColumnName.ToString() +
":""
 
+ dt.Rows[i][j].ToString() +
"""
);
                   
if
 
(j < dt.Columns.Count - 1)
                   
{
                       
Json.Append(
","
);
                   
}
               
}
               
Json.Append(
"}"
);
               
if
 
(i < dt.Rows.Count - 1)
               
{
                   
Json.Append(
","
);
               
}
           
}
       
}
       
Json.Append(
"]"
);
       
return
 
Json.ToString();
   
}
   
//列表数据转换到json数据
   
public string ObjectToJson<T>(string jsonName, IList<T> IL)
   
{
       
StringBuilder Json =
new
 
StringBuilder();
       
Json.Append(
"["
);
       
if
 
(IL.Count > 0)
       
{
           
for
 
(int i = 0; i < IL.Count; i++)
           
{
               
T obj = Activator.CreateInstance<T>();
               
Type type = obj.GetType();
               
PropertyInfo[] pis = type.GetProperties();
               
Json.Append(
"{"
);
               
for
 
(int j = 0; j < pis.Length; j++)
               
{
                   
Json.Append(pis[j].Name.ToString() +
":""
 
+ pis[j].GetValue(IL[i],
null
) +
"""
);
                   
if
 
(j < pis.Length - 1)
                   
{
                       
Json.Append(
","
);
                   
}
               
}
               
Json.Append(
"}"
);
               
if
 
(i < IL.Count - 1)
               
{
                   
Json.Append(
","
);
               
}
           
}
       
}
       
Json.Append(
"]"
);
       
return
 
Json.ToString();
   
}

 
页面Default.aspx
 
 
function
 
GetData()
   
{
    
$.getJSON(
     
"JsonData.ashx"
,
//产生Json数据的服务端页面
     
function
(json)
     
{
       
for
(
var
 
i=0;i<json.length;i++)
    
{
                    
//开始
                       
var
 
index=-1;
                       
var
 
txtTRLastIndex = findObj(
"txtTRLastIndex"
,document);
                       
var
 
rowID = parseInt(txtTRLastIndex.value);
                       
var
 
signFrame = findObj(
"SignFrame"
,document);
                       
//添加行
                       
var
 
newTR = signFrame.insertRow(signFrame.rows.length);
                       
newTR.id =
"SignItem"
 
+ rowID;
                       
//添加列:序号
                       
var
 
newNameTD=newTR.insertCell(0);
                       
//添加列内容
                       
newNameTD.innerHTML = newTR.rowIndex.toString();
                       
//添加列:姓名
                       
var
 
newNameTD=newTR.insertCell(1);
                       
//添加列内容
                       
newNameTD.innerHTML =
"<input name='txtName"
 
+ rowID +
"' id='txtName"
 
+ rowID +
"' value='"
+json[i].Name+
"' type='text' size='12' />"
;
                       
//添加列:电子邮箱
                       
var
 
newEmailTD=newTR.insertCell(2);
                       
//添加列内容
                       
newEmailTD.innerHTML =
"<input name='txtEMail"
 
+ rowID +
"' id='txtEmail"
 
+ rowID +
"' value='"
+json[i].Email+
"' type='text' size='20' />"
;
                       
//添加列:电话
                       
var
 
newTelTD=newTR.insertCell(3);
                       
//添加列内容
                       
newTelTD.innerHTML =
"<input name='txtTel"
 
+ rowID +
"' id='txtTel"
 
+ rowID +
"' value='"
+json[i].Phon+
"' type='text' size='10' />"
;
                       
//添加列:手机
                       
var
 
newMobileTD=newTR.insertCell(4);
                       
//添加列内容
                       
newMobileTD.innerHTML =
"<input name='txtMobile"
 
+ rowID +
"' id='txtMobile"
 
+ rowID +
"' value='"
+json[i].Move+
"' type='text' size='12' />"
;
                       
//添加列:公司名
                       
var
 
newCompanyTD=newTR.insertCell(5);
                       
//添加列内容
                       
newCompanyTD.innerHTML =
"<input name='txtCompany"
 
+ rowID +
"' id='txtCompany"
 
+ rowID +
"' value='"
+json[i].Pan+
"' type='text' size='20' />"
;
                       
 
                       
//添加下拉框
                       
var
 
newCompanyTD=newTR.insertCell(6);
                       
newCompanyTD.innerHTML =
"<select id='Select"
+rowID+
"'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option> </select>"
;
                       
 
                        
//动态选中下拉框
                         
for
(
var
 
j=0;j<document.getElementById(
"Select"
+rowID).options.length;j++)  
                           
{  
                               
if
(document.getElementById(
"Select"
+rowID).options[j].text==json[i].select)  
                               
index=j;  
                           

                              
if
(index>=0)
                                
document.getElementById(
"Select"
+rowID).options[index].selected=
true
;
                             
 
      
 
                       
//添加列:删除按钮
                       
var
 
newDeleteTD=newTR.insertCell(7);
                       
//添加列内容
                       
newDeleteTD.innerHTML =
"<div align='center' style='width:40px'><a href='javascript:;' onclick="DeleteSignRow('SignItem"
 
+ rowID +
"')">删除</a></div>"
;
                       
//将行号推进下一行
                       
txtTRLastIndex.value = (rowID + 1).toString();
    
}
     
}
     
 
     
 
     
)
   
}
datatable与json的转化

1将DataTable或Ilist<>转换成JSON格式

 

using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
/// <summary>
/// 将DataTable或Ilist<>转换成JSON格式
/// </summary>
public class ToJson
{
   
public ToJson()
   
{
   
}
//DataTable转成Json
   
public static string DataTableToJson(string jsonName, DataTable dt)
   
{
       
StringBuilder Json =
new
 
StringBuilder();
       
Json.Append(
"{""
 
+ jsonName +
"":["
);
       
if
 
(dt.Rows.Count > 0)
       
{
           
for
 
(int i = 0; i < dt.Rows.Count; i++)
           
{
               
Json.Append(
"{"
);
               
for
 
(int j = 0; j < dt.Columns.Count; j++)
               
{
                   
Json.Append(
"""
 
+ dt.Columns[j].ColumnName.ToString() +
"":""
 
+ dt.Rows[i][j].ToString() +
"""
);
                   
if
 
(j < dt.Columns.Count - 1)
                   
{
                       
Json.Append(
","
);
                   
}
               
}
               
Json.Append(
"}"
);
               
if
 
(i < dt.Rows.Count - 1)
               
{
                   
Json.Append(
","
);
               
}
           
}
       
}
       
Json.Append(
"]}"
);
       
return
 
Json.ToString();
   
}
//List转成json
   
public static string ObjectToJson<T>(string jsonName, IList<T> IL)
   
{
       
StringBuilder Json =
new
 
StringBuilder();
       
Json.Append(
"{""
 
+ jsonName +
"":["
);
       
if
 
(IL.Count > 0)
       
{
           
for
 
(int i = 0; i < IL.Count; i++)
           
{
               
T obj = Activator.CreateInstance<T>();
               
Type type = obj.GetType();
               
PropertyInfo[] pis = type.GetProperties();
               
Json.Append(
"{"
);
               
for
 
(int j = 0; j < pis.Length; j++)
               
{
                   
Json.Append(
"""
 
+ pis[j].Name.ToString() +
"":""
 
+ pis[j].GetValue(IL[i],
null
) +
"""
);
                   
if
 
(j < pis.Length - 1)
                   
{
                       
Json.Append(
","
);
                   
}
               
}
               
Json.Append(
"}"
);
               
if
 
(i < IL.Count - 1)
               
{
                   
Json.Append(
","
);
               
}
           
}
       
}
       
Json.Append(
"]}"
);
       
return
 
Json.ToString();
   
}
}

感谢站长 原文来自:http://www.suchso.com/projecteactual/jquery-datatable-list-json.html

时间: 2024-09-16 08:18:04

JQuery把DataTable、list<>数据转换成JSON数据的相关文章

java-extjs 树的问题,加载不出来,后台是用Java到数据读取的数据转换成json格式

问题描述 extjs 树的问题,加载不出来,后台是用Java到数据读取的数据转换成json格式 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@include file="common/common.jsp"%> <% pagemenustr += "addBtn(tb,'" + I18n.getText(&

C# DataTable 转换成JSON数据

原文:C# DataTable 转换成JSON数据   using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; using System.Web.Script.Serialization; namespace WsDemo { public class DataTableConvertJson { #regi

php实现数组中索引关联数据转换成json对象的方法_php技巧

本文实例讲述了php实现数组中索引关联数据转换成json对象的方法.分享给大家供大家参考.具体实现方法如下: public static function encode(&$var) { return '{'.implode(',',self::encodeExcute($var)).'}'; } private static function encodeExcute(&$var) { $json = array(); switch (gettype($var)) { case 'arr

数据库-怎么把MySql数据转换成Mongodb数据,跪求大神解答

问题描述 怎么把MySql数据转换成Mongodb数据,跪求大神解答 现在要做全国4级联动,想用Ajax做,但数据量太大.好不容易把数据导成sql的了, 但是数据库要用mongodb,不知道怎么弄了,求大神指点 解决方案 写个程序,jdbc从mysql把数据读出来,组装成想要的格式,再insert到mongodb中. 解决方案二: 对mongodb不熟悉.但是刚刚略微看了下是非关系型的数据库.在做持久操作的时候不用写sql直接操作方法即可. 那么我目前想到的思路是: 1.写个程序来检索你的mys

将字典或者数组转换成JSON数据或者字符串

将字典或者数组转换成JSON数据或者字符串 源码: NSDictionary+JSON.h 与 NSDictionary+JSON.m // // NSDictionary+JSON.h // Category // // Created by YouXianMing on 15-2-09. // Copyright (c) 2014年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> @interfa

html5-用纯javascript或者纯jQuery 调用中国气象网的json数据的代码

问题描述 用纯javascript或者纯jQuery 调用中国气象网的json数据的代码 用javascript或者jQuery 调用中国气象网 http://m.weather.com.cn/data/101050101.html 只能用javascript,jQuery,html5,css 效果是完整显示在页面上城市,一周天气 解决方案 最简单的,设置一个div,用#ajax.get下载网页,用("#yourdiv").html直接装入. 解决方案二: 直接jquery,GET请求

.NET 字符串如何转换成JSON数据

问题描述 varsys_item={"sys_attrprice":{"17":{"detailImage":"20160111130446844.jpg","detailPrice":"25.0000","Id":"6","sellStock":"10","stock":"10

Jquery通过ajax请求NodeJS返回json数据实例_jquery

最近看了NodeJS相关的,在网上查了下结合AJAX的应用,感觉应用前景还是不错的.为什么用这个组合呢? 1.NodeJS不需要安装,拷贝过去就可以使用,而环境变量可以只配置在当前cmd窗口,运行方便. 2.通过HTML的ajax请求,可以实现在不同的服务器上,可跨域获取数据. 3.通信数据格式灵活,可以是xml.json.binary等,数据适合任何平台. 在说说我的环境,我使用的是公司提供的电脑,有很多限制,比如是域中电脑,操作权限低,无法安装任何软件,无法修改计算机配置,无法使用U盘等等.

jquery ajax异步请求 接收返回json数据

例子  代码如下 复制代码 $('#send').click(function () {     $.ajax({         type : "GET",         url : "a.php",         dataType : "jsonp",         success : function (data) {             $.each(data.items, function (i, item) {