C#解析JSON数据全攻略

164 阅读2分钟

还在为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; }
}

文章转载自: 曲幽

原文链接: www.cnblogs.com/ymtianyu/p/…

体验地址: www.jnpfsoft.com/?from=001YH