生成json格式
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格式的更多相关文章
- Java Servlet生成JSON格式数据并用jQuery显示
1.Servlet通过json-lib生成JSON格式的数据 import java.io.IOException;import java.io.PrintWriter;import java.uti ...
- 使用JSONObject类来生成json格式的数据
JSONObject类不支持javabean转json 生成json格式数据的方式有: 1.使用JSONObject原生的来生成 2.使用map构建json格式的数据 3.使用javabean来构建j ...
- 如何使用fastJson来解析JSON格式数据和生成JSON格式数据
由于项目用到了JSON格式的数据,在网上搜索到了阿里的fastjson比较好用,特此记录fastjson用法,以备以后查询之用. decode: 首先创建一个JSON解析类: public class ...
- python 生成json格式文件,并存储到手机上
上代码 #!/usr/bin/env python # -*- encoding: utf-8 -*- import json import os import random "" ...
- php 生成json格式的数据
放到引入的公共函数里边 if (!function_exists('format_json')) { /** * 格式化API输出的json * @param $return_code string ...
- app开发历程————服务器端生成JSON格式数据,采用Unicode编码,隐藏中文
今天,问以前的同事,他们写接口按什么编码,怎么看到有\u的一些看不懂的内容,一问,原来是信息隐藏,防止信息泄漏. 然后在网上查了Java如何把中文转换成unicode编码,转自:http://blog ...
- eclipse 自动生成json格式的toString()方法
文本代码 {"${member.name()}":"${member.value}", "${otherMembers}"}
- Datatable 生成json格式
public string GetJsonFromDataTable(DataTable dt, int total, bool ShowFooter, string fields, string i ...
- 小记---------maxwell 一个可以实时读取mysql二进制日志binlog,并生成JSON格式的消息,作为生产者发送给kafka,Redis,文件或其他平台的应用程序
maxwell主要提供了下列功能 支持 SELECT * FROM table 的方式进行全量数据初始化 支持在主库发生failover后,自动回复binlog位置(GTID) ...
随机推荐
- fio 硬盘测试工具
一.windows环境 1. 安装fio:http://www.bluestop.org/fio/ 可以选择不同版本的安装,安装后在C:\Program Files\fio目录中可以找到fio的执行程 ...
- 阿里云Zabbix安装实践过程
1.配置阿里云zabbix yum源 [root@VM_0_8_centos ~]# rpm -ivh https://mirrors.aliyun.com/zabbix/zabbix/3.0/rhe ...
- MATLAB2014b parpool 报错,并行工具无法开启解决方法
笔者一直在用matlab2014b,第一次使用并行工具parpool,但在运行别人的程序的过程中一直出现一个错误: Starting parallel pool (parpool) using the ...
- 【Linux开发】linux设备驱动归纳总结(七):1.时间管理与内核延时
linux设备驱动归纳总结(七):1.时间管理与内核延时 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...
- (已解决)Could not open '/var/lib/nova/mnt/*/volume-*': Permission denied
[问题描述] 创建boot_from_volume的虚机时,磁盘后端为NFS,创建失败. [错误日志] nova-compute模块 Could not open '/var/lib/nova/mnt ...
- Visual Basic 中读取逗号分隔的文本文件
TextFieldParser 对象提供一种可以轻松而高效地分析结构化文本文件(如日志)的方法. TextFieldType 属性用于定义文件是带分隔符的文件还是具有固定宽度文本字段的文件. Dim ...
- 编写java 程序与Linux进行远程连接并运行linux下的脚本
我这里是通过连接到centos6.5的大数据集群的主节点,并通过运行hadoop的启动脚本来启动hadoop 本人采用的是SSH的方式连接 通过创建maven项目来编写代码,在编写代码之前需要先导入架 ...
- [Python3] 036 函数式编程 返回函数
目录 函数式编程 之 返回函数 1. 引子 2. 闭包 closure 函数式编程 之 返回函数 函数可以返回具体的值 也可以返回一个函数作为结果 1. 引子 1.1 定义一个普通函数 >> ...
- sql server如何精准匹配字符中的字符,绝对匹配
举例: 我现在是需要查询这字段里包含1的数据 我如果直接charindex,那么11,12也会被包含. 解决(1): select * from ( select '1,2,12,111' as s ...
- 小菜鸟之JAVA输入输出
Java流类图结构: 流的概念和作用 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观 ...