{
"Ishost": 0,
"items": [],
"calvisitcount": [0,19,1,...],
"modvisitcount": [
{"mod":0,"todaycount":0,"totalcount":1409245},
{"mod":1,"todaycount":0,"totalcount":0}
],
"lastlogin": 0,
"twlogincount": 0,
"lastgettime": 1381797259
}
| 庫 | 優點 | 缺點 |
|---|---|---|
| System.Text.Json (.NET Core 3.0+) | 零依賴、高性能、內建 | 舊 .NET Framework 需 NuGet |
| Newtonsoft.Json (Json.NET) | 生態成熟、API 豐富 | 需額外引用、稍慢 |
| JavaScriptSerializer | 無需引用 (System.Web.Extensions) | 已過時、不支持 .NET Core |
using System.Text.Json;
// 1. 定義 DTO
public class ModVisit {
public int mod { get; set; }
public int todaycount { get; set; }
public long totalcount { get; set; }
}
public class RootData {
public int Ishost { get; set; }
public int[] calvisitcount { get; set; }
public ModVisit[] modvisitcount { get; set; }
public int lastlogin { get; set; }
public int twlogincount { get; set; }
public long lastgettime { get; set; }
}
// 2. 解析
string json = "..."; // 去掉 _Callback(...) 包裹
var data = JsonSerializer.Deserialize<RootData>(json);
// 3. 取值
long firstTotal = data.modvisitcount[0].totalcount; // 1409245
int firstToday = data.modvisitcount[0].todaycount; // 0
// _Callback({...});
int start = json.IndexOf('{');
int end = json.LastIndexOf('}');
string pureJson = json.Substring(start, end - start + 1);
using JsonDocument = System.Text.Json.JsonDocument;
using var doc = JsonDocument.Parse(pureJson);
var root = doc.RootElement;
long total = root.GetProperty("modvisitcount")[0].GetProperty("totalcount").GetInt64();
const data = JSON.parse(pureJson);
const total = data.modvisitcount[0].totalcount; // 1409245
**拒絕正則/Substring 硬解析 JSON**。強類型反序列化編譯期檢查、IDE 提示、重構安全,維護成本最低。.NET 6+ 推薦
System.Text.Json,舊項目用Newtonsoft.Json遷移成本極低。