JSON工具:Encode、Decode及DataTable转JSON、转ArrayList等

本文介绍了一个用于处理JSON数据的工具类,包括序列化、反序列化、格式转换等功能,并提供了从DataTable转换到JSON字符串的方法。

转自:https://www.cnblogs.com/nxxshxf/p/5227503.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Collections;
using Newtonsoft.Json.Linq;
using System.Data;
using Newtonsoft.Json.Converters;

namespace JSON_Tools
{
    public class JSON
    {
        public static string DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss";
        public static string Encode(object o)
        {
            if (o == null || o.ToString() == "null") return null;
            if (o != null && (o.GetType() == typeof(String) || o.GetType() == typeof(string)))
            {
                return o.ToString();
            }
            IsoDateTimeConverter dt = new IsoDateTimeConverter();
            dt.DateTimeFormat = DateTimeFormat;
            return JsonConvert.SerializeObject(o, dt);
        }

        public static object Decode(string json)
        {
            if (String.IsNullOrEmpty(json)) return "";
            object o = JsonConvert.DeserializeObject(json);
            if (o.GetType() == typeof(String) || o.GetType() == typeof(string))
            {
                o = JsonConvert.DeserializeObject(o.ToString());
            }
            object v = toObject(o);
            return v;
        }
        public static object Decode(string json, Type type)
        {
            return JsonConvert.DeserializeObject(json, type);
        }
        private static object toObject(object o)
        {
            if (o == null) return null;
            if (o.GetType() == typeof(string))
            {
                //判断是否符合2010-09-02T10:00:00的格式                
                string s = o.ToString();
                if (s.Length == 19 && s[10] == 'T' && s[4] == '-' && s[13] == ':')
                {
                    o = System.Convert.ToDateTime(o);
                }
            }
            else if (o is JObject)
            {
                JObject jo = o as JObject;
                Hashtable h = new Hashtable();
                foreach (KeyValuePair<string, JToken> entry in jo)
                {
                    h[entry.Key] = toObject(entry.Value);
                }
                o = h;
            }
            else if (o is IList)
            {
                ArrayList list = new ArrayList();
                list.AddRange((o as IList));
                int i = 0, l = list.Count;
                for (; i < l; i++)
                {
                    list[i] = toObject(list[i]);
                }
                o = list;
            }
            else if (typeof(JValue) == o.GetType())
            {
                JValue v = (JValue)o;
                o = toObject(v.Value);
            }
            else
            {
            }
            return o;
        }

        public static ArrayList DataTable2ArrayList(DataTable data)
        {
            ArrayList array = new ArrayList();
            for (int i = 0; i < data.Rows.Count; i++)
            {
                DataRow row = data.Rows[i];
                Hashtable record = new Hashtable();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    object cellValue = row[j];
                    if (cellValue.GetType() == typeof(DBNull))
                    {
                        cellValue = null;
                    }
                    record[data.Columns[j].ColumnName] = cellValue;
                }
                array.Add(record);
            }
            return array;
        }

        /// <summary>        
        /// 将一个DataTable 转为一个JSON        
        /// </summary>        
        /// <param name="dt"></param>        
        /// <returns></returns>        
        public static string DataTable2Json(DataTable dt)
        {
            if (dt == null)
            {
                return "";
            }
            ArrayList dataAll = DataTable2ArrayList(dt);
            ArrayList data = new ArrayList();
            for (int i = 0, l = dataAll.Count; i < l; i++)
            {
                Hashtable record = (Hashtable)dataAll[i];
                if (record == null) continue;
                data.Add("'" + record + "'");
            }
            Hashtable result = new Hashtable();
            result["data"] = data;
            result["total"] = dataAll.Count;
            return JSON.Encode(dt);
        }

        /// <summary>        
        /// 通过一个datatable 返回一个json字符串
        /// </summary>        
        /// <param name="dt">按条件的datatable(分页内的列表)</param>        
        /// <param name="AllCount">datatable的总条数(分页时的总记录)</param>        
        /// <returns></returns>        
        public static string DataTable2Json(DataTable dt, int AllCount)
        {
            if (dt == null)
            {
                return "";
            }
            ArrayList dataAll = DataTable2ArrayList(dt);
            //实现一个内存分页(实际应该使用SQL分页)            
            ArrayList data = new ArrayList();
            for (int i = 0, l = dataAll.Count; i < l; i++)
            {
                Hashtable record = (Hashtable)dataAll[i];
                if (record == null) continue;
                data.Add(record);
            }
            Hashtable result = new Hashtable();
            result["data"] = data;
            result["total"] = AllCount;
            return JSON.Encode(result);
        }

        /// <summary>        
        /// 通过一个datatable 返回一个json字符串
        /// </summary>       
        /// <param name="dt">按条件的datatable(分页内的列表)</param>       
        /// <param name="AllCount">datatable的总条数(分页时的总记录)</param>      
        /// <returns></returns>        
        public static string DataTable2Json(DataTable dt, int AllCount, Hashtable hashtable)
        {
            if (dt == null)
            {
                return "";
            }
            ArrayList dataAll = DataTable2ArrayList(dt);
            //实现一个内存分页(实际应该使用SQL分页)            
            ArrayList data = new ArrayList();
            for (int i = 0, l = dataAll.Count; i < l; i++)
            {
                Hashtable record = (Hashtable)dataAll[i];
                if (record == null) continue;
                data.Add(record);
            }
            Hashtable result = new Hashtable();
            result = hashtable;
            result["data"] = data;
            result["total"] = AllCount;
            return JSON.Encode(result);
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="data">表dt</param>
        /// <param name="pageIndex">当前页索引</param>
        /// <param name="pageSize">每页的数目</param>
        /// <param name="pageCount">总数目</param>
        /// <returns></returns>
        public static DataTable dt2newdt(DataTable data, int pageIndex, int pageSize, int pageCount)
        {
            DataView dv = data.DefaultView;
            DataTable dt = dv.Table.Clone();
            for (int i = pageIndex * pageSize; i < (pageIndex + 1) * pageSize; i++)
            {
                if (i == pageCount)
                {
                    break;
                }
                dt.ImportRow(dv[i].Row);
            }
            return dt;
        }
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值