在對接第三方 API、處理動態配置、日志分析等場景中,JSON 結構往往不固定、層級深、字段多變。傳統強類型反序列化需預先定義實體類,靈活性不足。本文介紹一款輕量級的通用 JSON 解析器,通過 DOM 樹遍歷實現任意結構 JSON 的動態查詢與提取,無需實體類、零依賴、易擴展。
將 JSON 視為三類節點的遞歸組合:
{ "key": value }[value, value, ...]提供底層字符串操作:鍵提取、值提取、數組元素分割(正確處理巢狀結構)
protected List _GetCollection(string rawJson)
{
// 智能分割頂層逗號,忽略對象/數組內部的逗號
// 通過 nestLevel (大括號深度) 和 mNestLevel (中括號深度) 追蹤層級
}
封裝解析邏輯,提供豐富的查詢 API:
public class CommonJsonModel : CommonJsonModelAnalyzer
{
// 類型判斷
public bool IsValue() { ... }
public bool IsModel() { ... }
public bool IsCollection() { ... }
// 按鍵查詢(針對 Model 節點)
public string GetValue(string key) { ... }
public CommonJsonModel GetModel(string key) { ... }
public CommonJsonModel GetCollection(string key) { ... }
public List GetKeys() { ... }
// 針對 Collection 節點
public List GetCollection() { ... }
}
string json = @"{""total"": 0}";
var model = new CommonJsonModel(json);
string total = model.GetValue("total"); // "0"
string json = @"{""total"":0,""data"":{""377149574"": 1}}";
var model = new CommonJsonModel(json);
string val = model.GetModel("data").GetValue("377149574"); // "1"
string json = @"{""total"":0,""data"":{""377149574"":[{""cid"":""377149574""}]}}";
var model = new CommonJsonModel(json);
// 鏈式調用:取 data -> 取 377149574 數組 -> 取第 0 項對象 -> 取 cid 值
string cid = model
.GetModel("data")
.GetCollection("377149574")
.GetCollection()[0]
.GetValue("cid"); // "377149574"
| 特性 | 說明 |
|---|---|
| 零依賴 | 純 .NET Framework 實現,無 Newtonsoft.Json/System.Text.Json 依賴 |
| 無實體類 | 動態解析任意結構,適配頻繁變更的 API 響應 |
| 輕量級 | 核心代碼 < 300 行,易嵌入、易修改、易審計 |
| 鏈式 API | 流暢接口設計,代碼可讀性強 |
| 容錯性 | 鍵不存在返回 null,不拋異常,適合探查式解析 |
CommonJsonModel 實例System.Text.Json.Nodes.JsonNode 官方動態 API這款萬能 JSON 解析器以「無實體類、動態查詢、零依賴」三大特性,完美填補了強類型反序列化在動態場景下的能力空白。雖非高性能首選,但在 API 聯調、配置管理、日志分析等中低頻動態場景中,是極具性價比的利器。