获得省市 json 后台代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获得省市 json 后台代码相关的知识,希望对你有一定的参考价值。
string connString = ConfigurationManager.ConnectionStrings["connStr"].ToString();
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string sql = "select *from [dbo].[CrmAddress]";
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow[] arraySheng = dt.Select("CityLevel=1").OrderBy(e => e["CityCode"]).ToArray();
DataRow[] arrayShi = dt.Select("CityLevel=2").OrderBy(e => e["CityCode"]).ToArray();
Hashtable htshengshi = new Hashtable();
foreach (var itemsheng in arraySheng)
{
List<KeyValuePair<string, string>> shiList = new List<KeyValuePair<string, string>>();
foreach (var itemshi in arrayShi)
{
if (itemsheng["CityCode"].ToString().Trim() == itemshi["ParentID"].ToString().Trim())
{
shiList.Add(new KeyValuePair<string, string>(itemshi["CityCode"].ToString(), itemshi["CityName"].ToString()));
}
}
htshengshi.Add(itemsheng["CityCode"].ToString(), shiList);
}
DataTable dtsheng = new DataTable();
foreach (DataColumn col in dt.Columns)
{
dtsheng.Columns.Add(col.ColumnName);
}
foreach (var sheng in arraySheng)
{
dtsheng.Rows.Add(sheng.ItemArray);
}
StringBuilder jsonResult = new StringBuilder();
jsonResult.Append("{");
jsonResult.Append("\"result\":\"1\",");
jsonResult.Append("\"data\":{");
jsonResult.Append("\"province\":");
jsonResult.Append(ListToJsonString(dtsheng));
jsonResult.Append(",");
jsonResult.Append("\"city\":");
jsonResult.Append("[");
string fengefu = "";
foreach (DictionaryEntry itemSheng in htshengshi)
{
jsonResult.Append(fengefu+"{\"");
jsonResult.Append(itemSheng.Key.ToString());
jsonResult.Append("\":[");
List<KeyValuePair<string,string>> tempCityList= itemSheng.Value as List<KeyValuePair<string,string>>;
string fengefu2 = "";
foreach (KeyValuePair<string,string> itemShi in tempCityList)
{
jsonResult.Append(fengefu2+"{");
jsonResult.Append("\"");
jsonResult.Append(itemShi.Key.ToString());
jsonResult.Append("\":\"");
jsonResult.Append(itemShi.Value.ToString());
jsonResult.Append("\"}");
fengefu2 = ",";
}
jsonResult.Append("]");
jsonResult.Append("}");
fengefu = ",";
}
jsonResult.Append("]}}");
context.Response.ContentType = "text/plain";
context.Response.Write(jsonResult);
}
/// <summary>
/// 将DataSet中数据,json化
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public string ListToJsonString(DataTable source)
{
StringBuilder result = new StringBuilder();
string fengefu0 = "";
foreach (DataRow row in source.Rows)
{
result.Append(fengefu0 + "{");
fengefu0 = ",";
string fengefu = "";
foreach (DataColumn col in source.Columns)
{
result.Append(fengefu + "\"" + col.ColumnName + "\":" + "\"" + row[col].ToString().Trim() + "\"");
fengefu = ",";
}
result.Append("}");
}
result.Insert(0, "[");
result.Append("]");
return result.ToString();
}
以上是关于获得省市 json 后台代码的主要内容,如果未能解决你的问题,请参考以下文章