首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 解析 JSON 字符串提取字段的標準流程

     編輯:程式設計綜合問答

數據樣本

{
  "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

推薦:System.Text.Json 反序列化為強類型

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

若 JSON 包裹在回調函數中

// _Callback({...});
int start = json.IndexOf('{');
int end = json.LastIndexOf('}');
string pureJson = json.Substring(start, end - start + 1);

動態解析(無 DTO)

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();

JavaScript/前端同理

const data = JSON.parse(pureJson);
const total = data.modvisitcount[0].totalcount; // 1409245

**拒絕正則/Substring 硬解析 JSON**。強類型反序列化編譯期檢查、IDE 提示、重構安全,維護成本最低。.NET 6+ 推薦 System.Text.Json,舊項目用 Newtonsoft.Json 遷移成本極低。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved