还在为 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; }}
复制代码
文章转载自:曲幽
原文链接:https://www.cnblogs.com/ymtianyu/p/18997451
体验地址:http://www.jnpfsoft.com/?from=001YH
评论