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

相关推荐
钰fly1 天前
C#类型转换 显隐转换
c#
疯狂的挖掘机1 天前
记一次基于QT的图片操作处理优化思路(包括在图上放大缩小,截图,画线,取值等)
开发语言·数据库·qt
奇树谦1 天前
Qt | 利用map创建多个线程和定时器
网络·数据库·qt
用户47949283569151 天前
性能提升 4000%!我是如何解决 运营看板 不能跨库&跨库查询慢这个难题的
数据库·后端·postgresql
电商API&Tina1 天前
跨境电商 API 对接指南:亚马逊 + 速卖通接口调用全流程
大数据·服务器·数据库·python·算法·json·图搜索算法
robinson19881 天前
验证崖山数据库标量子查询是否带有CACHE功能
数据库·oracle·cache·自定义函数·崖山·标量子查询
老华带你飞1 天前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
kylezhao20191 天前
C#通过HSLCommunication库操作PLC用法
开发语言·c#
SelectDB1 天前
5 倍性能提升,Apache Doris TopN 全局优化详解|Deep Dive
数据库·apache
JIngJaneIL1 天前
基于springboot + vue房屋租赁管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端