html页面

 <input type="button" value="重新生成JSON" class="button1" id="createjson" />

javascript部分

 <script type="text/javascript">
$(function () {
//生成JSON
$("#createjson").click(function () {
$.post("NewsCategory.aspx?action=create", function (json) {
alert(json.msg);
});
});
});
</script>

后台代码

  protected void Page_Load(object sender, EventArgs e)
{
if (Request.Headers["X-Requested-With"] != null && Request.Headers["X-Requested-With"].ToLower() == "XMLHttpRequest".ToLower())
{
Response.Clear();
Response.ContentType = "application/json";
if (Request["action"] == "create")
{
Response.Write(CreateJson());
}
Response.End();
}
}
   /// <summary>
/// 生成商家类别Json
/// </summary>
/// <returns></returns>
protected string CreateJson()
{ System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
     //初始化(引用空间using System.Text;)
StringBuilder sb = new StringBuilder();
var list = Express.BLL.NewsCategory.Get();
foreach (var item in list)
{
if (sb.Length > )
sb.Append(",");
sb.Append(string.Format("{{\"id\":{0},\"name\":\"{1}\",\"pid\":{2},\"itemvalue\":\"{3}\"", item.Id, GetUnicode(item.ItemName), item.ParentId, item.ItemValue));
sb.Append("}");
}
     //返回与Web服务器上的指定虚拟路径相对应的物理文件路径
string filePath = Server.MapPath(@"/common/newscategoryJson.js");
     //创建一个新文件,并写入指定字符串,若目标文件已存在,则覆盖该文件
System.IO.File.WriteAllText(filePath, "[" + sb.ToString() + "]", System.Text.Encoding.UTF8);
return json.Serialize(new { code = , msg = "生成完成" });
}

汉字转为Unicode编码

 /// <summary>
/// 得到汉字的Unicode编码
/// </summary>
protected string GetUnicode(string text)
{
string result = "";
for (int i = ; i < text.Length; i++)
{
if ((int)text[i] > && (int)text[i] < )
{
result += text[i].ToString();
}
else
result += string.Format("\\u{0:x4}", (int)text[i]);
}
return result;
}

数据库部分

        /// 获取全部
/// </summary>
public List<Model.NewsCategory> Get()
{
string sql = "select * from NewsCategory order by case when ParentId=0 then Id*10000 else ParentId*10000+Id end";
List<Model.NewsCategory> list = new List<Model.NewsCategory>();
using (SqlDataReader dr = DBUtility.SqlHelper.ExecuteReader(ConnString.connReadonly, CommandType.Text, sql, null))
{
while (dr.Read())
{
Model.NewsCategory model = new Model.NewsCategory();
object obj;
obj = dr["Id"];
if (obj != null && obj != DBNull.Value)
{
model.Id = (int)obj;
}
obj = dr["SortValue"];
if (obj != null && obj != DBNull.Value)
{
model.SortValue = (int)obj;
}
obj = dr["ParentId"];
if (obj != null && obj != DBNull.Value)
{
model.ParentId = (int)obj;
}
model.ItemName = dr["ItemName"].ToString();
model.ItemValue=dr["ItemValue"].ToString();
list.Add(model);
}
}
return list;
}

运行结果
common/newscategoryJson.js

[
{"id":31,"name":"\u65b0\u95fb\u4e2d\u5fc3","pid":0,"itemvalue":"|0|"},
{"id":51,"name":"\u4f01\u4e1a\u5feb\u8baf","pid":31,"itemvalue":"|0|31|"},
{"id":52,"name":"\u4f01\u4e1a\u516c\u544a","pid":31,"itemvalue":"|0|31|"},
{"id":53,"name":"\u884c\u4e1a\u52a8\u6001","pid":31,"itemvalue":"|0|31|"},
{"id":91,"name":"\u65b0\u95fb\u4e2d\u5fc3","pid":31,"itemvalue":"|0|31|"},
{"id":93,"name":"\u4f01\u4e1a\u5feb\u8baf","pid":31,"itemvalue":"|0|31|"},
{"id":94,"name":"\u4f01\u4e1a\u516c\u544a","pid":31,"itemvalue":"|0|31|"},
{"id":180,"name":"\u6d4b\u8bd5","pid":31,"itemvalue":"|0|31|"},
{"id":181,"name":"\u6d4b\u8bd5111","pid":31,"itemvalue":"|0|31|"}, {"id":54,"name":"\u5173\u4e8e\u76df\u53cb\u634c\u634c","pid":0,"itemvalue":"|0|"},
{"id":55,"name":"\u4f01\u4e1a\u6982\u51b5","pid":54,"itemvalue":"|0|54|"},
{"id":56,"name":"\u4f01\u4e1a\u6587\u5316","pid":54,"itemvalue":"|0|54|"},
{"id":57,"name":"\u4f01\u4e1a\u53d1\u5c55","pid":54,"itemvalue":"|0|54|"}
......
]

涉及的知识点

1、Server.MapPath(string path);

2、System.IO.File.WriteAllText(sting path,string contents,Encoding encoding);

生成json格式的更多相关文章

  1. Java Servlet生成JSON格式数据并用jQuery显示

    1.Servlet通过json-lib生成JSON格式的数据 import java.io.IOException;import java.io.PrintWriter;import java.uti ...

  2. 使用JSONObject类来生成json格式的数据

    JSONObject类不支持javabean转json 生成json格式数据的方式有: 1.使用JSONObject原生的来生成 2.使用map构建json格式的数据 3.使用javabean来构建j ...

  3. 如何使用fastJson来解析JSON格式数据和生成JSON格式数据

    由于项目用到了JSON格式的数据,在网上搜索到了阿里的fastjson比较好用,特此记录fastjson用法,以备以后查询之用. decode: 首先创建一个JSON解析类: public class ...

  4. python 生成json格式文件,并存储到手机上

    上代码 #!/usr/bin/env python # -*- encoding: utf-8 -*- import json import os import random "" ...

  5. php 生成json格式的数据

    放到引入的公共函数里边 if (!function_exists('format_json')) { /** * 格式化API输出的json * @param $return_code string ...

  6. app开发历程————服务器端生成JSON格式数据,采用Unicode编码,隐藏中文

    今天,问以前的同事,他们写接口按什么编码,怎么看到有\u的一些看不懂的内容,一问,原来是信息隐藏,防止信息泄漏. 然后在网上查了Java如何把中文转换成unicode编码,转自:http://blog ...

  7. eclipse 自动生成json格式的toString()方法

    文本代码 {"${member.name()}":"${member.value}", "${otherMembers}"}

  8. Datatable 生成json格式

    public string GetJsonFromDataTable(DataTable dt, int total, bool ShowFooter, string fields, string i ...

  9. 小记---------maxwell 一个可以实时读取mysql二进制日志binlog,并生成JSON格式的消息,作为生产者发送给kafka,Redis,文件或其他平台的应用程序

    maxwell主要提供了下列功能     支持 SELECT * FROM table 的方式进行全量数据初始化     支持在主库发生failover后,自动回复binlog位置(GTID)     ...

随机推荐

  1. AE调用GP工具(创建缓冲区和相交为例)

    引用 Geoprocessing是ArcGIS提供的一个非常实用的工具,借由Geoprocessing工具可以方便的调用ArcToolBox中提供的各类工具,本文在ArcEngine9.2平台环境下总 ...

  2. mariadb(第二章)增删改 MariaDB 数据类型

    MariaDB 数据类型 MariaDB数据类型可以分为数字,日期和时间以及字符串值. 使用数据类型的原则:够用就行, 尽量使用范围小的,而不用大的 常用的数据类型 整数:int, bit 小数:de ...

  3. AI测试——旅程的终点

    在2019年6月,我产生了一个想法,即人工智能探索测试AIET(Artificial intelligence exploration test),大概用了一周时间来思考怎么把人工智能应用到测试领域, ...

  4. EVE-NG TOOLKIT在线安装

    功能如图修改EVE-NG管理IP,隐藏未知无效设备.更新或升级.添加设备支持等等 EVE-NG ToolKit中国镜像站官网在线安装:wget -q http://eve-ng.org:81/inst ...

  5. 电脑的sid

    SID的查询方法:1.Win键+R键,打开运行,输入CMD2.输入:whoami /user3.就可以看到本机的SID了 SID的修改方法1.下载NewSID软件,并打开 2.可以指定一个SID,也可 ...

  6. python基础之元祖tuple

    元祖是只读列表,不可哈希,可循环查询,可切片*儿子不能改,孙子可更改--元祖里面单个元素不能更改---元祖内列表可更改增:tu1+tu2查:tu1[index] tu1[start_index:end ...

  7. IIS调试

    点击调试程序的时候默认启动TFS内置的调试服务器http://localhost:51607/,在该处填写自己在IIS上配置的站点就能进入自己的站点调试http://mr.ciwong.com

  8. Sink - 汇聚点

    !!!1.Logger Sink 记录INFO级别的日志,通常用于调试.   属性说明: !channel –   !type – The component type name, needs to ...

  9. SpringCloud之Zuul 自定义filter

    实现过滤器很简单,只需要继承ZuulFilter,并实现ZuulFilter中的抽象方法. filterType():定义过滤器的类型,它有4种类型,分别是pre.post.routing和error ...

  10. 设计模式:建造者模式(Builder)

    流水作业大家应该都清楚吧!在流水作业中,我们可以将一些复杂的东西给构建出来,例如汽车.我们都知道汽车内部构件比较复杂,由很多部件组成,例如车轮.车门.发动机.方向盘等等,对于我们用户来说我们并不需要知 ...