C#解析JSON数据全攻略

还在为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快速开发平台

相关推荐
gc_22991 天前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
送秋三十五1 天前
MySQL DBA需要掌握的 7 个问题
数据库·mysql·dba
睡觉的时候不会困1 天前
MySQL 高可用方案之 MHA 架构搭建与实践
数据库·mysql·架构
kyle~1 天前
Qt---对话框QDialog
数据库·qt·microsoft
GBASE1 天前
“G”术时刻:南大通用GBase 8c数据库权限管理场景实践(三)
数据库
GottdesKrieges1 天前
OceanBase系统日志管理
数据库·oracle·oceanbase
小嵌同学1 天前
Linux:malloc背后的实现细节
大数据·linux·数据库
R瑾安1 天前
mysql安装(压缩包方式8.0及以上)
数据库·mysql
代码的余温1 天前
MySQL Cluster核心优缺点
数据库·mysql
almighty271 天前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别