C# 如何处理 JSON 数据_C# JSON 数据处理完整教程

来源:这里教程网 时间:2026-02-21 17:31:06 作者:

在 C# 中处理 JSON 数据是现代开发中非常常见的需求,尤其是在与 Web API 交互、配置读写或前后端数据传输时。C# 提供了多种方式来序列化和反序列化 JSON 数据,最常用的是 System.Text.Json(.NET Core 3.0+ 默认)和第三方库 Newtonsoft.Json(Json.NET)。本文将带你全面掌握 C# 中处理 JSON 的核心方法。

使用 System.Text.Json 进行 JSON 操作

System.Text.Json 是微软官方推荐的高性能 JSON 处理库,内置于 .NET Core 3.0 及以上版本,无需额外安装包。

1. 序列化对象为 JSON 字符串
将 C# 对象转换为 JSON 字符串:

using System.Text.Json;
<p>public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}</p><p>var person = new Person { Name = "张三", Age = 25 };
string jsonString = JsonSerializer.Serialize(person);
// 输出: {"Name":"张三","Age":25}
</p>

2. 反序列化 JSON 字符串为对象
将 JSON 字符串还原为 C# 对象:

string json = @"{""Name"":""李四"",""Age"":30}";
Person person = JsonSerializer.Deserialize<Person>(json);
Console.WriteLine(person.Name); // 输出: 李四

3. 格式化输出 JSON
让生成的 JSON 更易读:

var options = new JsonSerializerOptions { WriteIndented = true };
string prettyJson = JsonSerializer.Serialize(person, options);

4. 忽略 null 值或大小写不敏感反序列化
通过选项控制行为:

var options = new JsonSerializerOptions
{
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    PropertyNameCaseInsensitive = true
};

使用 Newtonsoft.Json(Json.NET)

Newtonsoft.Json 是功能更强大、灵活性更高的第三方库,支持更多特性,需通过 NuGet 安装:

Install-Package Newtonsoft.Json

1. 序列化与反序列化
用法类似,但命名空间不同:

using Newtonsoft.Json;
<p>string json = JsonConvert.SerializeObject(person);
Person person = JsonConvert.DeserializeObject<Person>(json);
</p>

2. 支持匿名对象和动态类型
Newtonsoft 支持直接解析到 dynamic:

dynamic obj = JsonConvert.DeserializeObject(json);
Console.WriteLine(obj.Name); // 输出属性值

3. 使用特性(Attribute)控制序列化行为
通过特性灵活定义字段映射:

public class Person
{
    [JsonProperty("full_name")]
    public string Name { get; set; }
<pre class="brush:php;toolbar:false;">[JsonIgnore]
public int Age { get; set; }

}

处理复杂 JSON 结构

实际开发中,JSON 往往嵌套复杂,可能包含数组、字典或未知结构。

1. 解析 JSON 数组

string jsonArray = "[{""Name"":""A""},{""Name"":""B""}]";
List<Person> people = JsonSerializer.Deserialize<List<Person>>(jsonArray);

2. 使用 JsonDocument(只读解析)
适合不需要映射到类的场景,如解析配置片段:

using JsonDocument doc = JsonDocument.Parse(jsonString);
JsonElement root = doc.RootElement;
string name = root.GetProperty("Name").GetString();
int age = root.GetProperty("Age").GetInt32();

3. 使用 Dictionary 解析未知结构
当字段不确定时:

var data = JsonSerializer.Deserialize<Dictionary<string, object>>(json);
foreach (var kvp in data)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

常见问题与最佳实践

处理 JSON 时注意以下几点可避免常见错误:

确保类属性名与 JSON 字段匹配,或使用特性映射 日期格式默认可能不符合预期,可通过
JsonSerializerOptions
设置转换器
处理大文件时建议使用
Utf8JsonReader
流式读取,节省内存
Newtonsoft.Json 支持更多类型(如 DataSet),但性能略低于 System.Text.Json 若项目已用 Newtonsoft,不建议强行切换,保持一致性更重要

基本上就这些。根据项目框架选择合适的 JSON 处理方式,掌握序列化、反序列化、格式控制和异常处理,就能高效应对大多数场景。

相关推荐

热文推荐