生成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) ...
随机推荐
- 语音识别LD3320
一.概述 1.芯片介绍 LD3320 是一颗基于非特定人语音识(SI-ASR:Speaker-Independent Automatic Speech Recognition)技术的语音识/声控芯片 ...
- 应用安全 - 工具|平台 - CDN - 使用|命令 - 汇总
简介 用途 使用缓存适应高并发请求 功能 ()抗DDOS ()隐藏真实IP 全球DNS地址分布:http://www.ab173.com/dns/dns_world.php全球IP地址段分布:http ...
- 【Linux开发】linux设备驱动归纳总结(八):2.总线、设备和驱动的关系
linux设备驱动归纳总结(八):2.总线.设备和驱动的关系 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...
- JAVA实验三及总结
JAVA第五周作业 Java实验报告三 第一题 1.已知字符串:"this is a test of java".按要求执行以下操作:(要求源代码.结果截图.) (1).统计该字符 ...
- 吉首大学2019年程序设计竞赛-F 天花乱坠
题目链接:https://ac.nowcoder.com/acm/contest/992/F 题意:给定正n边形,边长为100,以每条边的中点连线构成新的正n边形,无限循环下去,求所有边的长度和. 思 ...
- 微信多开脚本(Windows,Mac)
微信多开 以下内容仅用于学习使用.严禁用于非法用途,违者自负. Windows 多开 Windows 版本的微信在一些比较新的版本好像限制了多开,我们这里提供一个版本(也是官方的).https://p ...
- Ruby学习中(条件判断, 循环, 异常处理)
一. 条件判断 详情参看:https://www.runoob.com/ruby/ruby-decision.html 1.详情实例(看看就中了) #---------------# # LOL场均人 ...
- nohup重定向到其它的日志文件
如果使用nohup命令提交作业,那么在缺省情况下该作业的所有输出都被重定向到一个名为nohup.out的文件中,除非另外指定了输出文件: nohup command > myout.file 2 ...
- springboot2整合zookeeper集成curator
步骤: 1- pom.xml <dependency> <groupId>org.apache.curator</groupId> <artifactId&g ...
- git解决pre-commit hook failed的问题
最近在提交前端代码的时候发现提交不上去,一直报错 一.错误详情 二.错误分析 1.刚开始用vsCode提交,后更改为命令提交,依旧报错: 2.经过查询资料,发现是pre-commit钩子的原因. ...