ASP 返回 JSON 格式的完整指南**
在 Web 开发中,JSON(JavaScript Object Notation)因其轻量级、易解析和与 JavaScript 的天然亲和力,已成为前后端数据交互的主流格式之一,对于使用 ASP(Active Server Pages,包括经典 ASP 和 ASP.NET)的开发者来说,如何正确返回 JSON 数据至关重要,本文将分别介绍在经典 ASP 和 ASP.NET(Web Forms 及 MVC)中返回 JSON 格式数据的常用方法。
经典 ASP (Classic ASP) 返回 JSON
经典 ASP 本身没有内置的 JSON 序列化对象,因此我们需要借助第三方组件(如 Scripting.Dictionary 对象构建 JSON 字符串,或使用成熟的 JSON 库如 json2.js 的服务端版本,或微软的 MSXML 解析器等),这里介绍一种不依赖外部组件,使用 Scripting.Dictionary 和 ADODB.Stream(或直接字符串拼接)来构建和返回 JSON 的方法。
示例:使用 Scripting.Dictionary 构建并返回 JSON
假设我们有一个数据库查询结果,需要将其转换为 JSON 格式返回。
<%
' 设置响应内容类型为 JSON
Response.ContentType = "application/json"
Response.Charset = "utf-8"
' 模拟数据库查询结果 - 实际中应从数据库获取
' 假设我们有一个用户列表
Dim users(2)
Set users(0) = CreateObject("Scripting.Dictionary")
users(0).Add "id", 1
users(0).Add "name", "张三"
users(0).Add "email", "zhangsan@example.com"
Set users(1) = CreateObject("Scripting.Dictionary")
users(1).Add "id", 2
users(1).Add "name", "李四"
users(1).Add "email", "lisi@example.com"
Set users(2) = CreateObject("Scripting.Dictionary")
users(2).Add "id", 3
users(2).Add "name", "王五"
users(2).Add "email", "wangwu@example.com"
' 构建 JSON 字符串
Dim jsonString
jsonString = "["
For i = LBound(users) To UBound(users)
If i > LBound(users) Then
jsonString = jsonString & ","
End If
jsonString = jsonString & "{"
Dim key
For Each key In users(i).Keys
jsonString = jsonString & """" & key & """:" & """" & users(i)(key) & """"
' 如果不是最后一个键,添加逗号
If Not IsLastKey(users(i), key) Then
jsonString = jsonString & ","
End If
Next
jsonString = jsonString & "}"
Next
jsonString = jsonString & "]"
' 输出 JSON
Response.Write(jsonString)
' 辅助函数:判断是否为 Dictionary 的最后一个键
Function IsLastKey(dict, currentKey)
Dim keys, i
keys = dict.Keys
IsLastKey = (currentKey = keys(dict.Count - 1))
End Function
' 清理 (Scripting.Dictionary 通常不需要显式释放,但好习惯是释放)
For i = LBound(users) To UBound(users)
Set users(i) = Nothing
Next
Set users = Nothing
%>
说明:
Response.ContentType = "application/json":这是关键,告诉客户端返回的是 JSON 数据。Response.Charset = "utf-8":确保字符编码正确,避免中文乱码。- 构建 JSON 字符串:上述代码使用循环和
Scripting.Dictionary手动拼接 JSON 字符串,对于复杂对象,这种方法会比较繁琐且容易出错。 Response.Write:输出最终的 JSON 字符串。
更推荐的方法(经典 ASP):
为了更方便地处理 JSON,强烈建议在经典 ASP 项目中使用成熟的 JSON 解析/生成库,
- ASPJSON:一个流行的开源 JSON 库 for Classic ASP。
- json2.asp:可以从
json2.js改编而来。
使用这些库,你可以像在 JavaScript 中一样创建和操作 JSON 对象,然后序列化为字符串,使用 ASPJSON):
' 需要先引入 ASPJSON 的类文件
' <!--#include file="JSON_2.0.4.asp"--> ' 假设库文件名为此
<%
Response.ContentType = "application/json"
Response.Charset = "utf-8"
Set json = New JSONobject
json("status") = "success"
json("message") = "数据获取成功"
json("data") = Array("item1", "item2", "item3")
Set jsonData = New JSONarray
jsonData.add json ' 假设我们要返回一个包含多个对象的数组
Response.Write jsonData.toString()
Set jsonData = Nothing
Set json = Nothing
%>
ASP.NET 返回 JSON
ASP.NET 提供了更强大和便捷的方式来处理 JSON。
ASP.NET Web Forms
在 ASP.NET Web Forms 中,你可以使用 JavaScriptSerializer (System.Web.Script.Serialization) 或 Newtonsoft.Json (Json.NET) 第三方库。Newtonsoft.Json 是目前更常用和功能更丰富的选择。
示例:使用 JavaScriptSerializer (System.Web.Script.Serialization)
using System;
using System.Web.Script.Serialization; // 需要引用 System.Web.Extensions
protected void Page_Load(object sender, EventArgs e)
{
// 设置响应内容类型
Response.ContentType = "application/json";
Response.Charset = "utf-8";
// 准备数据
var user = new
{
id = 1,
name = "赵六",
email = "zhaoliu@example.com",
joinDate = DateTime.Now
};
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonString = js.Serialize(user);
// 输出 JSON
Response.Write(jsonString);
// 防止后续控件渲染
Response.End();
}
示例:使用 Newtonsoft.Json (Json.NET)
首先需要通过 NuGet 安装 Newtonsoft.Json 包。
using Newtonsoft.Json;
using System;
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
Response.Charset = "utf-8";
var user = new
{
id = 2,
name = "钱七",
email = "qianqi@example.com",
isActive = true
};
string jsonString = JsonConvert.SerializeObject(user, Formatting.Indented); // Formatting.Indented 美化输出
Response.Write(jsonString);
Response.End();
}
ASP.NET MVC / ASP.NET Core
在 ASP.NET MVC 及其后续版本 ASP.NET Core 中,返回 JSON 数据变得异常简单。
ASP.NET MVC 示例:
using System.Web.Mvc; // 需要引用 System.Web.Mvc
public class UserController : Controller
{
public ActionResult GetUser(int id)
{
var user = new { UserId = id, Name = "孙八", Email = "sunba@example.com" };
// 方法1:使用 Json() 方法
// 第一个参数:要序列化的对象
// 第二个参数:JSON请求的行为 (JsonRequestBehavior.AllowGet 允许 GET 请求返回 JSON,默认只允许 POST)
return Json(user, JsonRequestBehavior.AllowGet);
}
}
ASP.NET Core MVC 示例:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var user = new { UserId = id, Name = "周九", Email = "zhoujiu@example.com" };
// 在 ASP.NET Core 中,Json() 方法默认返回 application/json 内容类型
// 并且默认允许 GET 请求(除非配置了其他选项)
return Json(user);
// 或者更现代的方式:使用 Ok() 并隐式序列化
// return Ok(user);
}
}
ASP.NET Core 中使用 System.Text.Json (内置):
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
var forecast = new[] {
new { Date = DateTime.Now, TemperatureC = 25, Summary = "晴" }
};
// 可以手动控制序列化选项
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 驼峰命名
WriteIndented = true
};
return new ContentResult
{
Content = JsonSerializer.Serialize(forecast, options),
ContentType = "application/json",
StatusCode = 200
};
}
}
总结与最佳实践
- 设置正确的 Content-Type:无论使用哪种技术,务必将
Response.ContentType(或等效的响应头)



还没有评论,来说两句吧...