本文整理四大 JSON 核心操作類別,涵蓋動態物件轉換、序列化/反序列化、資料表轉 JSON、JSON 格式驗證、AJAX 統一回傳格式,程式碼開箱即用,適合直接納入專案共用函式庫。
基於 JavaScriptSerializer,支援:
DataReader、DataSet、DataTable → JSONDynamicJsonObject + DynamicJsonConverter)
public static class JsonConverter
{
// 物件 → JSON(可選日期轉換)
public static string Serialize(object obj, bool dateConvert = false);
// JSON → 動態物件
public static dynamic ConvertJson(string json);
// 自定義查詢物件 → 動態物件
public static dynamic JsonClass(object obj);
// DataReader → JSON 字串
public static string ToJson(IDataReader reader);
// DataSet → JSON(多資料表)
public static string ToJson(DataSet ds);
// DataTable → JSON(指定根節點名)
public static string ToJson(DataTable dt, string jsonName);
// DataTable → JSON(預設根節點)
public static string ToJson(DataTable dt);
// 內部:型別格式化(字串/日期/布林/位元組/Guid)
private static string StringFormat(string str, Type type);
// 內部:特殊字元跳脫
public static string String2Json(string s);
}
string json = @"{""name"":""Tom"",""age":25,""skills"":[""C#"",""SQL""]}";
dynamic obj = JsonConverter.ConvertJson(json);
Console.WriteLine(obj.name); // Tom
Console.WriteLine(obj.age); // 25
foreach (var s in obj.skills) // 動態陣列迭代
Console.WriteLine(s);
依賴 Newtonsoft.Json 套件,提供型別安全的泛型序列化/反序列化。
public static class JsonHelper
{
// 物件 → 縮排 JSON
public static string ToJson(object t);
// 物件 → JSON(可選忽略 null 值)
public static string ToJson(object t, bool ignoreNull);
// JSON → 強型別物件
public static T FromJson(string json) where T : class;
// List → JSON(使用 DataContractJsonSerializer)
public static string ListToJson(IList
var user = new { Id = 1, Name = "Alice", Roles = new[] { "Admin", "User" } };
string json = JsonHelper.ToJson(user, ignoreNull: true);
// {"Id":1,"Name":"Alice","Roles":["Admin","User"]}
var restored = JsonHelper.FromJson(json);
Console.WriteLine(restored.Name); // Alice
不依賴任何 JSON 程式庫,透過字元狀態機驗證字串是否為合法 JSON(物件或陣列),並回傳錯誤位置索引。
public static class JsonSplit
{
// 簡單驗證
public static bool IsJson(string json);
// 驗證並取得錯誤索引
public static bool IsJson(string json, out int errIndex);
}
{}、陣列開始/結束 []、鍵值對分隔 :、項目分隔 ,、字串跳脫 \、引號配對。 \r\n\t\0 。errIndex 便於前端高亮錯誤位置。標準化 AJAX 回應結構:IsError、Message、Data,提供靜態工廠方法快速建立成功/失敗結果。
public class AjaxResult
{
public bool IsError { get; private set; }
public string Message { get; set; }
public object Data { get; set; }
private AjaxResult() { }
// 靜態工廠方法
public static AjaxResult Error() => new AjaxResult { IsError = true };
public static AjaxResult Error(string msg) => new AjaxResult { IsError = true, Message = msg };
public static AjaxResult Success() => new AjaxResult { IsError = false };
public static AjaxResult Success(string msg) => new AjaxResult { IsError = false, Message = msg };
public static AjaxResult Success(object data) => new AjaxResult { IsError = false, Data = data };
public static AjaxResult Success(object data, string msg) => new AjaxResult { IsError = false, Data = data, Message = msg };
// 序列化為 JSON 字串(供 Controller 直接回傳)
public override string ToString() => new JavaScriptSerializer().Serialize(this);
}
public ActionResult GetUser(int id)
{
var user = _service.GetById(id);
if (user == null)
return Content(AjaxResult.Error("使用者不存在").ToString());
return Content(AjaxResult.Success(user, "查詢成功").ToString());
}
// 前端 JS 接收統一處理
// $.post('/GetUser', {id:1}, function(res) {
// if (res.IsError) showError(res.Message);
// else renderUser(res.Data);
// });
| 類別 | 建議使用場景 | 相依套件 | 備註 |
|---|---|---|---|
| JsonConverter | 舊專案、DataTable/DataSet 轉 JSON、需動態解析 | System.Web.Extensions | 基於 JavaScriptSerializer,效能較 Newtonsoft 慢 |
| JsonHelper | 新專案、高效能序列化、強型別反序列化 | Newtonsoft.Json | 推薦主力庫,支援 .NET Standard/Core |
| JsonSplit | 輕量驗證、無法引入套件環境 | 無 | 純演算法,適合前置檢查 |
| AjaxResult | 所有 AJAX 端點統一回傳格式 | System.Web.Extensions | 可配合 JsonHelper.ToJson 序列化 |
JsonSerializer.Serialize/Deserialize 替代 JsonHelper。JsonDocument、JsonElement 替代動態解析。JsonNode(.NET 6+)提供可變動 DOM 操作。Common.Utilities.Json(Class Library)。Common.Utilities.Json。Newtonsoft.Json(供 JsonHelper 使用)。System.Web.Extensions(供 JavaScriptSerializer、AjaxResult 使用)。擁有這套工具類,即可應付 90% 以上的 JSON 處理需求,專注業務邏輯開發。