在 ASP.NET(WebForms / MVC / Web API)中,DataContractJsonSerializer 是 .NET Framework 內建的 JSON 處理器,無需第三方庫即可實現物件與 JSON 字串雙向轉換。本文提供完整的擴展方法、實體類定義、前端 AJAX 呼叫與後端 Handler 實現,涵蓋 GET 取得 JSON 與 POST 接收 JSON 兩大場景。
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
public static class JsonHelper
{
/// 物件序列化為 JSON 字串(UTF-8)
public static string ToJson(this object obj)
{
if (obj == null) return null;
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// JSON 字串反序列化為指定型別物件
public static T FromJson(this string json)
{
if (string.IsNullOrEmpty(json)) return default(T);
var serializer = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)serializer.ReadObject(ms);
}
}
}
[DataContract]
public class CarInfo
{
[DataMember] public string Make { get; set; }
[DataMember] public string Model { get; set; }
[DataMember] public int Year { get; set; }
[DataMember] public string Color { get; set; }
}
關鍵點:類別需標記[DataContract],屬性標記[DataMember],否則不會被序列化。
public class GetJsonHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var car = new CarInfo
{
Make = "Tesla",
Model = "Model 3",
Year = 2023,
Color = "Red"
};
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(car.ToJson());
}
public bool IsReusable => false;
}
public class PostJsonHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string json = context.Request["postjson"]; // 前端傳參名稱
if (string.IsNullOrEmpty(json))
{
context.Response.Write("{\"success\":false,\"msg\":\"empty json\"}");
return;
}
var car = json.FromJson();
bool valid = !string.IsNullOrEmpty(car.Make)
&& !string.IsNullOrEmpty(car.Model)
&& !string.IsNullOrEmpty(car.Color)
&& car.Year > 0;
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write("{\"success\":" + valid.ToString().ToLower() + "}");
}
public bool IsReusable => false;
}
$('#getJson').click(function () {
$.ajax({
url: 'GetJsonHandler.ashx',
type: 'GET',
dataType: 'json',
success: function (car) {
alert('品牌:' + car.Make + '\n型號:' + car.Model + '\n年份:' + car.Year + '\n顏色:' + car.Color);
},
error: function (xhr, status, err) {
alert('請求失敗:' + status);
}
});
});
$('#postJson').click(function () {
var car = { Make: "Ford", Model: "Mustang", Year: 1967, Color: "Blue" };
// 需引用 json2.js 或現代瀏覽器原生 JSON.stringify
var jsonStr = JSON.stringify(car);
$.ajax({
url: 'PostJsonHandler.ashx',
type: 'POST',
data: { postjson: jsonStr }, // 以表單欄位傳遞 JSON 字串
dataType: 'json',
success: function (res) {
alert(res.success ? '後端驗證通過' : '資料不完整');
}
});
});
DataContractJsonSerializer 將 DateTime 序列化為 /Date(1335205592410)/ 格式,前端需自行解析或使用 JSON.parse 搭配 reviver 函數。charset=utf-8。Make),前端建議保持一致或使用 camelCase 映射。Newtonsoft.Json (Json.NET) 或 .NET Core 內建 System.Text.Json,速度更快且功能更豐富。// GET 回傳
{"Color":"Red","Make":"Tesla","Model":"Model 3","Year":2023}
// POST 成功回傳
{"success":true}
透過內建 DataContractJsonSerializer 即可快速實現前後端 JSON 交互,無額外依賴,適合輕量級專案或受限環境。