C#-序列化和反序列化-JsonHelper-通用实体泛型ServerResponse转json字符串-DataTable转json字符串
context.Response.ContentType = "application/json";
context.Response.AddHeader("Access-Control-Allow-Origin","*");
context.Response.AddHeader("AccessAccess-Control-Allow-Methods","*");
!但是注意web.config中需要指定Methods
context.Response.AddHeader("Access-Control-Allow-Headers","*");//"x-requested-with,content-type"
跨越设置添加的头不能和web.config重复,只需要设置一处
http://blog.csdn.net/caozhangyingfei0109/article/details/53439377
另外
《Newtonsoft.Json高级用法》
JsonHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Data;
using System.IO;
using Newtonsoft.Json;
using System.Runtime.Serialization.Json;
using AotuBusiness.Entity;
namespace WebHelper
{
public class JsonHelper
{
private string _error = string.Empty;
private bool _success = true;
public string extraMSG = string.Empty;
public JToken data;
public List<object> data_obj;
public JArray array;
public string error
{
get
{
return this._error;
}
set
{
if (value != "")
{
this._success = false;
}
this._error = value;
}
}
public bool success
{
get
{
return this._success;
}
set
{
if (value)
{
this._error = string.Empty;
}
this._success = value;
}
}
#region dataTable转换成Json格式
/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTableJson(DataTable dt, string ChartType)
{
int intJ = 0;
int intI = 0;
string categoryName = string.Empty;
// 如果是饼图的话,移除categoryName,且只统计最后一行总数
if (ChartType == "Pie3D")
{
intJ = 1;
intI = 12;
}
else
{
intJ = 0;
categoryName = "\"categoryName\":\"时间\",";
}
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{");
jsonBuilder.Append(categoryName);
jsonBuilder.Append("\"dataType\":\"MutiColumnDefinition\",");
jsonBuilder.Append("\"tableData");
//jsonBuilder.Append(dt.TableName);
jsonBuilder.Append("\":{");
for (int j = intJ; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":");
jsonBuilder.Append("[");
for (int i = intI; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("\"" + dt.Rows[i][j].ToString() + "\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
jsonBuilder.Append(",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
jsonBuilder.Append("\"summaryColumns\":[");
for (int k = 1; k < dt.Columns.Count; k++)
{
jsonBuilder.Append("{");
jsonBuilder.Append("\"seriesName\":\"" + dt.Columns[k].ColumnName + "\",");
jsonBuilder.Append("\"columnName\":\"" + dt.Columns[k].ColumnName + "\",");
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
#endregion dataTable转换成Json格式
#region dataTable转换成Json格式
/// <summary>
/// gxw 2015-11-9 add
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTableToJSON(DataTable dt, string dtName)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jw = new JsonTextWriter(sw))
{
JsonSerializer ser = new JsonSerializer();
jw.WriteStartObject();
jw.WritePropertyName(dtName);
jw.WriteStartArray();
foreach (DataRow dr in dt.Rows)
{
jw.WriteStartObject();
foreach (DataColumn dc in dt.Columns)
{
jw.WritePropertyName(dc.ColumnName);
ser.Serialize(jw, dr[dc].ToString());
}
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.WriteEndObject();
sw.Close();
jw.Close();
}
return sb.ToString();
}
#endregion
#region dataTable转换成Json格式
/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}
#endregion dataTable转换成Json格式
#region 通用对象转成Json格式
/// <summary>
/// 实体序列化
/// 调用示例 需要加注解 DataContract DataMember (添加Serialization程序集)
/// ServerResponse<TestEntity> sr = ServerResponse<TestEntity>.create(0, "请求测试成功", xxxEntity);
/// string json = JsonHelper.ServerResponseToJson(sr);
/// Add header like Response.AddHeader("Content-type", "application/json;charset=UTF-8"); before retruning value if you want
/// to show pretty json pattern,defalut maybe html/text.Seri
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="d"></param>
/// <returns></returns>
public static string ObjectToJsonForSerialize<T>(T d)
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
MemoryStream msObj = new MemoryStream();
//将序列化之后的Json格式数据写入流中
js.WriteObject(msObj, d);
msObj.Position = 0;
//从0这个位置开始读取流中的数据
StreamReader sr = new StreamReader(msObj, Encoding.UTF8);
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
return json;
}
#endregion 通用对象转成Json格式
#region json字符串的反序列化 需要加注解 DataContract DataMember
/// <summary>
/// json字符串的反序列化 (能否支持嵌套未测试)
/// 20171113 江节胜 新增
/// 需要加注解 DataContract DataMember (添加Serialization程序集)
/// 示例:List<XXXEntity> twoList = JsonToObjectForSerialize<List<XXXEntity>>(jsonStr);
/// </summary>
/// <returns></returns>
public static T JsonToObjectForSerialize<T>(String jsonStr)
{
if (String.IsNullOrWhiteSpace(jsonStr))
{
return default(T);
}
T model;
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonStr)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(T));
model = (T)deseralizer.ReadObject(ms);// //反序列化ReadObject
}
return model;
}
#endregion json字符串的反序列化 需要加注解 DataContract DataMember
#region 通用对象转成Json格式
/// <summary>
/// 实体序列化
/// 不需要加注解 DataContract DataMember ,实体应该需要get set,需要添加Newtonsoft.Json.dll
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="d"></param>
/// <returns></returns>
public static string ObjectToJsonNotForSerialize<T>(T d)
{
JsonSerializerSettings jsetting = new JsonSerializerSettings();
jsetting.NullValueHandling = NullValueHandling.Ignore;
return JsonConvert.SerializeObject(d, Formatting.Indented, jsetting);
}
#endregion 通用对象转成Json格式
#region json反序列成实体
/// <summary>
/// json反序列成实
/// 不需要加注解 DataContract DataMember, 实体应该需要get set,需要添加Newtonsoft.Json.dll,支持List
/// 示例:List<XXXEntity> twoList = JsonToObjectNotForSerialize<List<XXXEntity>>(jsonStr);
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="d"></param>
/// <returns></returns>
public static T JsonToObjectNotForSerialize<T>(String jsonStr)
{
if (String.IsNullOrWhiteSpace(jsonStr))
{
return default(T);
}
T model = JsonConvert.DeserializeObject<T>(jsonStr);
return model;
}
#endregion json反序列成实体
#region 获取json 中值
/// <summary>
///获取json 中值
/// </summary>
/// <param name="jsonStr"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetJsonValue(string jsonStr, string key)
{
string result = string.Empty;
if (!string.IsNullOrWhiteSpace(jsonStr))
{
key = "\"" + key.Trim('"') + "\"";
int index = jsonStr.IndexOf(key) + key.Length + 1;
if (index > key.Length + 1)
{
//先截逗号,若是最后一个,截“}”号,取最小值
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}
//index = json.IndexOf('"', index + key.Length + 1) + 1;
result = jsonStr.Substring(index, end - index);
//过滤引号或空格
result = result.Trim(new char[] { '"', ' ', '\'' });
}
}
return result;
}
#endregion 获取json 中值
#region 获取json 中值方法2
/// <summary>
/// 获取json 中值方法2 (多层嵌套的未测试)
/// </summary>
/// <param name="jsonStr"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetJsonValueByJObject(string jsonStr, string key)
{
string result = string.Empty;
if (!string.IsNullOrWhiteSpace(jsonStr))
{
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);
result = jo[key].ToString();//要不要判断是否有key?
}
return result;
}
#endregion 获取json 中值2
}
}
正文到此结束