還在為C#處理網絡API返回的復雜JSON數據頭疼嗎?據統計,90%的開發者都曾在JSON解析上栽過跟頭!
本文將手把手教你用C#輕松玩轉JSON數據:- HttpClient獲取網絡JSON數據- System.Text.Json動態解析技巧- 強類型模型轉換實戰- 特殊字符/日期格式處理方案- 完整可運行代碼示例
🔍 一、為什么JSON是C#開發必修課?
現代Web API中95%的數據交換采用JSON格式。無論是調用天氣API、支付接口,還是處理云服務返回數據,JSON解析都是核心技能!
?? 二、四步搞定網絡JSON數據
1. 獲取數據 - HttpClient最佳實踐
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://api.example.com/data");
var jsonString = await response.Content.ReadAsStringAsync();
關鍵點:使用using自動釋放資源,異步方法提升性能
2. 動態解析 - 快速讀取字段
using System.Text.Json;
var jsonDoc = JsonDocument.Parse(jsonString);
string name = jsonDoc.RootElement.GetProperty("user").GetProperty("name").GetString();
適用場景:快速提取少量字段,無需創建完整模型
3. 強類型解析 - 推薦方案!
public class User {public string Name { get; set; }public int Age { get; set; }public DateTime RegisterDate { get; set; }
}var user = JsonSerializer.Deserialize<User>(jsonString, new JsonSerializerOptions {PropertyNameCaseInsensitive = true // 忽略大小寫
});
優勢:編譯時檢查 + 智能提示 + 高可維護性
4. 特殊場景處理
- 日期格式轉換:
options.Converters.Add(new DateTimeConverter("yyyy-MM-dd"));
- 處理JSON注釋:
options.ReadCommentHandling = JsonCommentHandling.Skip;
🚨 三、避坑指南
-?NULL引用異常:給屬性設置默認值?public string Name { get; set; } = string.Empty;
-?字段缺失:使用[JsonIgnore]
忽略不存在的屬性
-?性能陷阱:大文件解析用JsonDocument
替代JObject
💻 四、完整代碼示例
using System.Text.Json;public async Task<WeatherData> GetWeatherAsync() {using var httpClient = new HttpClient();// 獲取杭州天氣數據var response = await httpClient.GetAsync("https://api.weather.com/v3?location=hangzhou");response.EnsureSuccessStatusCode();var json = await response.Content.ReadAsStringAsync();// 強類型解析return JsonSerializer.Deserialize<WeatherData>(json, new JsonSerializerOptions {PropertyNameCaseInsensitive = true,NumberHandling = JsonNumberHandling.AllowReadingFromString});
}// 定義數據模型
public class WeatherData {public string Location { get; set; } = string.Empty;public double Temperature { get; set; }public string Unit { get; set; } = "Celsius";[JsonPropertyName("wind_speed")]public double WindSpeed { get; set; }
}
文章轉載自:曲幽
原文鏈接:C#解析JSON數據全攻略 - 曲幽 - 博客園
體驗地址:JNPF快速開發平臺