JSON 工具类

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

public class DataToJson
{
/// <summary>
/// 把object对象序列化成json字符串
/// </summary>
/// <param name="obj">序列话的实例</param>
/// <returns>序列化json字符串</returns>
public static string SerializeToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}

/// <summary>
/// 把json字符串反序列化成Object对象
/// </summary>
/// <param name="json">json字符串</param>
/// <returns>对象实例</returns>
public static Object DeserializeFromJson(string json)
{
return JsonConvert.DeserializeObject(json);
}

/// <summary>
/// 把json字符串反序列化成泛型T
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="json">json字符串</param>
/// <returns>泛型T</returns>
public static T DeserializeFromJson<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
///<summary>
/// 返回easyui/extjs中datagrid使用的json格式
///</summary>
///<param name="dt">datatable数据</param>
///<param name="count">总的条数</param>
///<returns></returns>
public static string DataTableToJson(DataTable dt, int count)
{
StringBuilder sbjson = new StringBuilder();
sbjson.Append("{");
sbjson.Append("\"total\":" + count + ",\"rows\":[");
if (dt != null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i > 0)
{
sbjson.Append(",");
sbjson.Append("{");
foreach (DataColumn dc in dt.Columns)
{
string value = StringPlus.HtmlEncode(dt.Rows[i][dc.ColumnName].ToString().Trim());
if (dt.Columns.IndexOf(dc) > 0)
{
sbjson.Append(",");
sbjson.Append("\"" + dc.ColumnName + "\":\"" + value + "\"");
}
else
{
sbjson.Append("\"" + dc.ColumnName + "\":\"" + value + "\"");
}
}
sbjson.Append("}");
}
else
{
sbjson.Append("{");
foreach (DataColumn dc in dt.Columns)
{
string value = StringPlus.HtmlEncode(dt.Rows[i][dc.ColumnName].ToString().Trim());
if (dt.Columns.IndexOf(dc) > 0)
{
sbjson.Append(",");
sbjson.Append("\"" + dc.ColumnName + "\":\"" + value + "\"");
}
else
{
sbjson.Append("\"" + dc.ColumnName + "\":\"" + value + "\"");
}
}
sbjson.Append("}");
}
}
}
sbjson.Append("]}");

return sbjson.ToString();
}

/// <summary>
/// 根据DataTable生成Json树结构
/// </summary>
/// <param name="tabel">数据源</param>
/// <param name="idCol">ID列</param>
/// <param name="txtCol">Text列</param>
/// <param name="rela">关系字段</param>
/// <param name="pId">父ID</param>
public static string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId)
{
string rlt = "";
StringBuilder result = new StringBuilder();
StringBuilder sb = new StringBuilder();
result.Append(sb.ToString());
sb.Length = 0;
if (tabel.Rows.Count > 0)
{
sb.Append("[");
string filer = string.Format("{0}=‘{1}‘", rela, pId);
DataRow[] rows = tabel.Select(filer);
if (rows.Length > 0)
{
foreach (DataRow row in rows)
{
sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"state\":\"open\"");
if (tabel.Select(string.Format("{0}=‘{1}‘", rela, row[idCol])).Length > 0)
{
sb.Append(",\"children\":");
GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
result.Append(sb.ToString());
sb.Length = 0;
}
result.Append(sb.ToString());
sb.Length = 0;
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
}
sb.Append("]");
result.Append(sb.ToString());
rlt = result.ToString();
sb.Length = 0;
}
return rlt;
}

#region json转Datatable
/// <summary>
/// 根据Json返回DateTable,JSON数据格式如:
/// {table:[{column1:1,column2:2,column3:3},{column1:1,column2:2,column3:3}]}
/// </summary>
/// <param name="strJson">Json字符串</param>
/// <returns></returns>
public static DataTable JsonToDataTable(string strJson)
{
//取出表名
var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
string strName = rg.Match(strJson).Value;
DataTable tb = null;
//去除表名
strJson = strJson.Substring(strJson.IndexOf("[") + 1);
strJson = strJson.Substring(0, strJson.IndexOf("]"));

//获取数据
rg = new Regex(@"(?<={)[^}]+(?=})");
MatchCollection mc = rg.Matches(strJson);
for (int i = 0; i < mc.Count; i++)
{
string strRow = mc[i].Value;
string[] strRows = strRow.Split(‘,‘);

//创建表
if (tb == null)
{
tb = new DataTable();
tb.TableName = strName;
foreach (string str in strRows)
{
var dc = new DataColumn();
string[] strCell = str.Split(‘:‘);
dc.ColumnName = strCell[0];
tb.Columns.Add(dc);
}
tb.AcceptChanges();
}

//增加内容
DataRow dr = tb.NewRow();
for (int r = 0; r < strRows.Length; r++)
{
dr[r] = strRows[r].Split(‘:‘)[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
}
tb.Rows.Add(dr);
tb.AcceptChanges();
}

return tb;
}
#endregion

#region 根据DataTable生成EasyUI Tree Json树结构
/// <summary>
/// 根据DataTable生成EasyUI Tree Json树结构
/// </summary>
/// <param name="tabel">数据源</param>
/// <param name="idCol">ID列</param>
/// <param name="txtCol">Text列</param>
/// <param name="url">节点Url</param>
/// <param name="rela">关系字段</param>
/// <param name="pId">父ID</param>
/// <example>string json = GetTreeJsonByTable(dt, "id", "name", "url", "fatherid", "0");</example>
private string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string url, string rela, object pId)
{
StringBuilder result = new StringBuilder();
StringBuilder sb = new StringBuilder();
result.Append(sb.ToString());
sb.Length = 0;
if (tabel.Rows.Count > 0)
{
sb.Append("[");
string filer = string.Format("{0}=‘{1}‘", rela, pId);
DataRow[] rows = tabel.Select(filer);
if (rows.Length > 0)
{
foreach (DataRow row in rows)
{
sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"attributes\":\"" + row[url] + "\",\"state\":\"open\"");
if (tabel.Select(string.Format("{0}=‘{1}‘", rela, row[idCol])).Length > 0)
{
sb.Append(",\"children\":");
GetTreeJsonByTable(tabel, idCol, txtCol, url, rela, row[idCol]);
result.Append(sb.ToString());
sb.Length = 0;
}
result.Append(sb.ToString());
sb.Length = 0;
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
}
sb.Append("]");
result.Append(sb.ToString());
sb.Length = 0;
}
return result.ToString();
}
#endregion

}

时间: 2024-10-11 06:14:22

JSON 工具类的相关文章

Code片段 : .properties属性文件操作工具类 &amp; JSON工具类

摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “贵专” — 泥瓦匠 一.java.util.Properties API & 案例 java.util.Properties 是一个属性集合.常见的api有如下: load(InputStream inStream)  从输入流中读取属性 getProperty(String key)  根据key,获取属性值 getOrDefault(Object key, V defaultValue)

Json工具类 - JsonUtils.java

Json工具类,提供Json与对象之间的转换. 源码如下:(点击下载 - JsonUtils.java . gson-2.2.4.jar ) import java.lang.reflect.Type; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * Json工具类 * */ @SuppressWarnings("unchecked") public

Json工具类,实现了反射将整个Object转换为Json对象的功能,支持Hibernate的延迟加

package com.aherp.framework.util; import java.lang.reflect.Array;import java.lang.reflect.Method;import java.util.Collection;import java.util.Iterator;import java.util.Map; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONO

Java Web返回JSON工具类

Web项目中经常涉及到AJAX请求返回JSON和JSONP数据.JSON数据在服务器端和浏览器端传输,本质上就是传输字符串,不过这个字符串符合JSON语法格式.浏览器端会按照普通文本的格式接收JSON字符串,最终JSON字符串转成JSON对象通过JavaScript实现.目前部分浏览器(IE9以下浏览器没有提供)和常用的JS库都提供了JSON序列化和反序列化的方法,如jQuery的AJAX请求可以指定返回的数据格式,包括text.json.jsonp.xml.html等. Web服务器端只要把J

强大的Java Json工具类

转自: https://blog.csdn.net/u014676619/article/details/49624165 import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.

HttpClientUntils工具类的使用及注意事项(包括我改进的工具类和Controller端的注意事项【附 Json 工具类】)

HttpClient工具类(我改过): package com.taotao.httpclient; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.Ur

Java常用工具类---image图片处理工具类、Json工具类

package com.jarvis.base.util; import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;im

JSON工具类

1 import java.sql.Timestamp; 2 import java.util.Collection; 3 import java.util.Date; 4 5 import org.soul.util.json.JsonDateValueProcessor; 6 import org.soul.util.json.JsonIgnorePropertyFilter; 7 8 import net.sf.json.JSONArray; 9 import net.sf.json.JS

json工具类封装与解析

package com.chinatelecom.personalcustom.common.util; import java.io.IOException; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.Obj

Object 转 json 工具类

/** * 把数据对象转换成json字符串 DTO对象形如:{"id" : idValue, "name" : nameValue, ...} * 数组对象形如:[{}, {}, {}, ...] map对象形如:{key1 : {"id" : idValue, "name" : * nameValue, ...}, key2 : {}, ...} * * @param object * @return */ public s