最近做手机开发,后台vs2010,access=>json<=前端Android,ios
网上的例子真的很少,苦逼了一周,本地浏览器是可以看到结果,但是Android和ios的屌丝们都耐不住了,MB的,解析不了啊,这是个肿么情况。哎~~~
天天傻瓜式的上网查资料,打开百度,输入"net如何将json以包的形式传递给前端。",java的倒是有几个,.net的例子一个都没有,真想ctmd。本来想找外部资源问问,倒是给了个例子,md什么都冒得,就一个Newtonsoft.dll,感觉自己被鄙视了。冷静后,发誓一定将json传参搞定....
废话不多说,直接上代码。
新添加一个ashx的页面取名为“GetJson”
json类
public
class GetJson : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetNoStore();
context.Response.Clear();
context.Response.ContentType = " application/json ";
context.Response.Charset = " utf-8 ";
string action = context.Request[ " action "].ToString();
string param = context.Request[ " params "].ToString().Replace( @" "" ", "").Replace( " { ", "").Replace( " } ", "");
context.Response.Write(Write(action, param));
}
public string ReturnJson()
{
DataTable dt = new BLL.category().GetList( "");
// return ToJson(dt);
return CreateJsonParameters(dt);
}
/// <summary>
/// 将一个数据表转换成一个JSON字符串,在客户端可以直接转换成二维数组。
/// </summary>
/// <param name="source"> 需要转换的表。 </param>
/// <returns></returns>
public static string DataTableToJson(DataTable source)
{
if (source.Rows.Count == 0)
return "";
StringBuilder sb = new StringBuilder( " [ ");
foreach (DataRow row in source.Rows)
{
sb.Append( " [ ");
for ( int i = 0; i < source.Columns.Count; i++)
{
sb.Append( ' " ' + row[i].ToString() + " \", ");
}
sb.Remove(sb.Length - 1, 1);
sb.Append( " ], ");
}
sb.Remove(sb.Length - 1, 1);
sb.Append( " ] ");
return sb.ToString();
}
/// <summary>
/// 反回JSON数据到前台
/// </summary>
/// <param name="dt"> 数据表 </param>
/// <returns> JSON字符串 </returns>
public string CreateJsonParameters(DataTable dt)
{
StringBuilder JsonString = new StringBuilder();
// Exception Handling
if (dt != null && dt.Rows.Count > 0)
{
JsonString.Append( " { ");
JsonString.Append( " \"TableInfo\":[ ");
for ( int i = 0; i < dt.Rows.Count; i++)
{
JsonString.Append( " { ");
for ( int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
JsonString.Append( " \" " + dt.Columns[j].ColumnName.ToString() + " \": " + " \" " + dt.Rows[i][j].ToString() + " \", ");
}
else if (j == dt.Columns.Count - 1)
{
JsonString.Append( " \" " + dt.Columns[j].ColumnName.ToString() + " \": " + " \" " + dt.Rows[i][j].ToString() + " \" ");
}
}
/**/
/* end Of String */
if (i == dt.Rows.Count - 1)
{
JsonString.Append( " } ");
}
else
{
JsonString.Append( " }, ");
}
}
JsonString.Append( " ]} ");
return JsonString.ToString();
}
else
{
return null;
}
}
public static string ToJsons(DataTable dt)
{
Dictionary< string, object> dic = new Dictionary< string, object>();
int index = 0;
foreach (DataRow dr in dt.Rows)
{
Dictionary< string, object> result = new Dictionary< string, object>();
foreach (DataColumn dc in dt.Columns)
{
result.Add(dc.ColumnName, dr[dc].ToString());
}
dic.Add(index.ToString(), result);
index++;
}
return ToJson(dic);
}
public static string ToJson( object obj)
{
/// / 首先,当然是JSON序列化
// DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
/// / 定义一个stream用来存发序列化之后的内容
// Stream stream = new MemoryStream();
// serializer.WriteObject(stream, obj);
/// / 从头到尾将stream读取成一个字符串形式的数据,并且返回
// stream.Position = 0;
// StreamReader streamReader = new StreamReader(stream);
// return streamReader.ReadToEnd();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
StringBuilder sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
return sb.ToString();
}
}
// http://localhost :27784/admin/GetJson.aspx?uuid=3C075461B9B0&platformCode=IPHONE&platformVersion=5.1&appVersion=1.0&action=200&sign=464532A3157ED106931C569442F1A0B7¶ms={channel_id:1,parent_id:0}
// 获取栏目
public string GetLanMu( string action, string param)
{
BLL.category bllCagetory = new BLL.category();
string str = string.Empty;
string[] s = param.Split( ' , ');
switch (action)
{
case " 200 ": // 栏目
string channel_id = s[ 0].Split( ' : ')[ 1];
string parent_id = s[ 1].Split( ' : ')[ 1];
DataTable dt = bllCagetory.GetList( " channel_id= " + channel_id + " and parent_id= " + parent_id);
string[] strColumnName = { " id ", " title ", " img_url " };
str = GetjsonByDT(dt, strColumnName, parent_id, action);
break;
case " 201 ": // 运动项目
string parent_id1 = s[ 0].Split( ' : ')[ 1];
DataTable dt1 = bllCagetory.GetList( " parent_id= " + parent_id1);
string[] strColumnName1 = { " id ", " title ", " img_url " };
str = GetjsonByDT(dt1, strColumnName1, parent_id1, action);
break;
case " 202 ": // 动作分解
string parent_id2 = s[ 0].Split( ' : ')[ 1];
DataTable dt2 = bllCagetory.GetList( " parent_id= " + parent_id2);
string[] strColumnName2 = { " id ", " title ", " img_url " };
str = GetjsonByDT(dt2, strColumnName2, parent_id2, action);
break;
default:
break;
}
return str;
}
public string GetActionName( string action)
{
string s = string.Empty;
switch (action)
{
case " 200 ":
s = " menu "; break;
case " 201 ":
s = " menu_sport "; break;
case " 202 ":
s = " action "; break;
case " 203 ":
s = " action_info "; break;
default:
break;
}
return s;
}
public string GetjsonByDT(DataTable dt, string[] strcolumnName, string id, string action)
{
StringBuilder JsonString = new StringBuilder();
// Exception Handling
if (dt != null && dt.Rows.Count > 0)
{
JsonString.Append( " { ");
JsonString.Append( " \"parent_id\": " + id + " , ");
string title = "";
if ( new BLL.category().GetModel( int.Parse(id)) != null)
{
title = " \" " + new BLL.category().GetModel( int.Parse(id)).title + " \" ";
}
else
{
title = " \"\" ";
}
JsonString.Append( " \"title\": " + title + "" + " , ");
JsonString.Append( " \" " + GetActionName(action) + " \":[ ");
if (dt.Rows.Count > 0)
{
for ( int i = 0; i < dt.Rows.Count; i++)
{
string categoroyid = dt.Rows[i][ " id "].ToString();
DataTable dtphoto = new BLL.photo().GetList( 100, " category_id= " + categoroyid, " id asc ").Tables[ 0];
JsonString.Append( " { ");
string str = string.Empty;
foreach ( string s in strcolumnName)
{
if (s == " img_url ")
{
if (dtphoto.Rows.Count > 0)
{
str += " \"action_info\":[ ";
foreach (DataRow dr in dtphoto.Rows)
{
string simage = string.Empty;
DataTable dtphoto_album = new BLL.photo_album().GetList( " photo_id= " + dr[ " id "].ToString()).Tables[ 0];
if (dtphoto_album.Rows.Count > 0)
{
foreach (DataRow dr1 in dtphoto_album.Rows)
{
simage += " {\" ";
simage += s + " \": " + " \"http://liuhuawenmile.vicp.cc " + dr1[ " small_img "] + " \" ";
simage += " }, ";
}
simage = simage.Substring( 0, simage.Length - 1);
}
if (simage.Length == 0)
{
simage = " {\"image_url\":\"-1\"} ";
}
str += " {\"id\": " + " \" " + dr[ " id "].ToString() + " \", ";
str += " \"title\": " + " \" " + dr[ " title "].ToString() + " \", ";
str += " \"image\":[ " + simage + " ]}, ";
}
str = str.Substring( 0, str.Length - 1);
str += " ] ";
}
}
else
{
str += " \" " + s + " \": " + " \" " + dt.Rows[i][s].ToString() + " \", ";
}
}
JsonString.Append(str.Substring( 0, str.Length - 1));
/**/
/* end Of String */
if (i == dt.Rows.Count - 1)
{
JsonString.Append( " } ");
}
else
{
JsonString.Append( " }, ");
}
}
JsonString.Append( " ]} ");
}
}
return JsonString.ToString();
}
public string Write( string action, string param)
{
try
{
return " {\"Code\":\"1\", " + " \"Message\":\" " + " 成功 " + " \",\"Result\": " + ToJson(GetLanMu(action, param)) + " ,\"OperationTime\": " + " \" " + DateTime.Now.ToString() + " \"} ";
}
catch (Exception ex)
{
return " {\"Code\":\"-1\", " + " \"Message\":\" " + ex.ToString() + " \", " + " \"Result\":\"null\",\"OperationTime\": " + " \" " + DateTime.Now.ToString() + " \"} ";
}
}
}
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetNoStore();
context.Response.Clear();
context.Response.ContentType = " application/json ";
context.Response.Charset = " utf-8 ";
string action = context.Request[ " action "].ToString();
string param = context.Request[ " params "].ToString().Replace( @" "" ", "").Replace( " { ", "").Replace( " } ", "");
context.Response.Write(Write(action, param));
}
public string ReturnJson()
{
DataTable dt = new BLL.category().GetList( "");
// return ToJson(dt);
return CreateJsonParameters(dt);
}
/// <summary>
/// 将一个数据表转换成一个JSON字符串,在客户端可以直接转换成二维数组。
/// </summary>
/// <param name="source"> 需要转换的表。 </param>
/// <returns></returns>
public static string DataTableToJson(DataTable source)
{
if (source.Rows.Count == 0)
return "";
StringBuilder sb = new StringBuilder( " [ ");
foreach (DataRow row in source.Rows)
{
sb.Append( " [ ");
for ( int i = 0; i < source.Columns.Count; i++)
{
sb.Append( ' " ' + row[i].ToString() + " \", ");
}
sb.Remove(sb.Length - 1, 1);
sb.Append( " ], ");
}
sb.Remove(sb.Length - 1, 1);
sb.Append( " ] ");
return sb.ToString();
}
/// <summary>
/// 反回JSON数据到前台
/// </summary>
/// <param name="dt"> 数据表 </param>
/// <returns> JSON字符串 </returns>
public string CreateJsonParameters(DataTable dt)
{
StringBuilder JsonString = new StringBuilder();
// Exception Handling
if (dt != null && dt.Rows.Count > 0)
{
JsonString.Append( " { ");
JsonString.Append( " \"TableInfo\":[ ");
for ( int i = 0; i < dt.Rows.Count; i++)
{
JsonString.Append( " { ");
for ( int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
JsonString.Append( " \" " + dt.Columns[j].ColumnName.ToString() + " \": " + " \" " + dt.Rows[i][j].ToString() + " \", ");
}
else if (j == dt.Columns.Count - 1)
{
JsonString.Append( " \" " + dt.Columns[j].ColumnName.ToString() + " \": " + " \" " + dt.Rows[i][j].ToString() + " \" ");
}
}
/**/
/* end Of String */
if (i == dt.Rows.Count - 1)
{
JsonString.Append( " } ");
}
else
{
JsonString.Append( " }, ");
}
}
JsonString.Append( " ]} ");
return JsonString.ToString();
}
else
{
return null;
}
}
public static string ToJsons(DataTable dt)
{
Dictionary< string, object> dic = new Dictionary< string, object>();
int index = 0;
foreach (DataRow dr in dt.Rows)
{
Dictionary< string, object> result = new Dictionary< string, object>();
foreach (DataColumn dc in dt.Columns)
{
result.Add(dc.ColumnName, dr[dc].ToString());
}
dic.Add(index.ToString(), result);
index++;
}
return ToJson(dic);
}
public static string ToJson( object obj)
{
/// / 首先,当然是JSON序列化
// DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
/// / 定义一个stream用来存发序列化之后的内容
// Stream stream = new MemoryStream();
// serializer.WriteObject(stream, obj);
/// / 从头到尾将stream读取成一个字符串形式的数据,并且返回
// stream.Position = 0;
// StreamReader streamReader = new StreamReader(stream);
// return streamReader.ReadToEnd();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
StringBuilder sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
return sb.ToString();
}
}
// http://localhost :27784/admin/GetJson.aspx?uuid=3C075461B9B0&platformCode=IPHONE&platformVersion=5.1&appVersion=1.0&action=200&sign=464532A3157ED106931C569442F1A0B7¶ms={channel_id:1,parent_id:0}
// 获取栏目
public string GetLanMu( string action, string param)
{
BLL.category bllCagetory = new BLL.category();
string str = string.Empty;
string[] s = param.Split( ' , ');
switch (action)
{
case " 200 ": // 栏目
string channel_id = s[ 0].Split( ' : ')[ 1];
string parent_id = s[ 1].Split( ' : ')[ 1];
DataTable dt = bllCagetory.GetList( " channel_id= " + channel_id + " and parent_id= " + parent_id);
string[] strColumnName = { " id ", " title ", " img_url " };
str = GetjsonByDT(dt, strColumnName, parent_id, action);
break;
case " 201 ": // 运动项目
string parent_id1 = s[ 0].Split( ' : ')[ 1];
DataTable dt1 = bllCagetory.GetList( " parent_id= " + parent_id1);
string[] strColumnName1 = { " id ", " title ", " img_url " };
str = GetjsonByDT(dt1, strColumnName1, parent_id1, action);
break;
case " 202 ": // 动作分解
string parent_id2 = s[ 0].Split( ' : ')[ 1];
DataTable dt2 = bllCagetory.GetList( " parent_id= " + parent_id2);
string[] strColumnName2 = { " id ", " title ", " img_url " };
str = GetjsonByDT(dt2, strColumnName2, parent_id2, action);
break;
default:
break;
}
return str;
}
public string GetActionName( string action)
{
string s = string.Empty;
switch (action)
{
case " 200 ":
s = " menu "; break;
case " 201 ":
s = " menu_sport "; break;
case " 202 ":
s = " action "; break;
case " 203 ":
s = " action_info "; break;
default:
break;
}
return s;
}
public string GetjsonByDT(DataTable dt, string[] strcolumnName, string id, string action)
{
StringBuilder JsonString = new StringBuilder();
// Exception Handling
if (dt != null && dt.Rows.Count > 0)
{
JsonString.Append( " { ");
JsonString.Append( " \"parent_id\": " + id + " , ");
string title = "";
if ( new BLL.category().GetModel( int.Parse(id)) != null)
{
title = " \" " + new BLL.category().GetModel( int.Parse(id)).title + " \" ";
}
else
{
title = " \"\" ";
}
JsonString.Append( " \"title\": " + title + "" + " , ");
JsonString.Append( " \" " + GetActionName(action) + " \":[ ");
if (dt.Rows.Count > 0)
{
for ( int i = 0; i < dt.Rows.Count; i++)
{
string categoroyid = dt.Rows[i][ " id "].ToString();
DataTable dtphoto = new BLL.photo().GetList( 100, " category_id= " + categoroyid, " id asc ").Tables[ 0];
JsonString.Append( " { ");
string str = string.Empty;
foreach ( string s in strcolumnName)
{
if (s == " img_url ")
{
if (dtphoto.Rows.Count > 0)
{
str += " \"action_info\":[ ";
foreach (DataRow dr in dtphoto.Rows)
{
string simage = string.Empty;
DataTable dtphoto_album = new BLL.photo_album().GetList( " photo_id= " + dr[ " id "].ToString()).Tables[ 0];
if (dtphoto_album.Rows.Count > 0)
{
foreach (DataRow dr1 in dtphoto_album.Rows)
{
simage += " {\" ";
simage += s + " \": " + " \"http://liuhuawenmile.vicp.cc " + dr1[ " small_img "] + " \" ";
simage += " }, ";
}
simage = simage.Substring( 0, simage.Length - 1);
}
if (simage.Length == 0)
{
simage = " {\"image_url\":\"-1\"} ";
}
str += " {\"id\": " + " \" " + dr[ " id "].ToString() + " \", ";
str += " \"title\": " + " \" " + dr[ " title "].ToString() + " \", ";
str += " \"image\":[ " + simage + " ]}, ";
}
str = str.Substring( 0, str.Length - 1);
str += " ] ";
}
}
else
{
str += " \" " + s + " \": " + " \" " + dt.Rows[i][s].ToString() + " \", ";
}
}
JsonString.Append(str.Substring( 0, str.Length - 1));
/**/
/* end Of String */
if (i == dt.Rows.Count - 1)
{
JsonString.Append( " } ");
}
else
{
JsonString.Append( " }, ");
}
}
JsonString.Append( " ]} ");
}
}
return JsonString.ToString();
}
public string Write( string action, string param)
{
try
{
return " {\"Code\":\"1\", " + " \"Message\":\" " + " 成功 " + " \",\"Result\": " + ToJson(GetLanMu(action, param)) + " ,\"OperationTime\": " + " \" " + DateTime.Now.ToString() + " \"} ";
}
catch (Exception ex)
{
return " {\"Code\":\"-1\", " + " \"Message\":\" " + ex.ToString() + " \", " + " \"Result\":\"null\",\"OperationTime\": " + " \" " + DateTime.Now.ToString() + " \"} ";
}
}
}