C# 如何将数据保存为 JSON 文件及如何打开该文件
在 C# 开发中,JSON(JavaScript Object Notation)因其轻量级、易读性强的特点,常被用于数据存储和交换,本文将详细介绍如何将 C# 对象或数据保存为 JSON 文件,以及如何打开和读取这些 JSON 文件,涵盖基础操作、异常处理及进阶技巧。
C# 中保存数据为 JSON 文件的核心方法
在 C# 中,保存 JSON 文件主要通过序列化(Serialization)实现,即将 C# 对象转换为 JSON 格式的字符串,再写入文件。.NET 提供了多种 JSON 序列化工具,其中最常用的是 System.Text.Json(.NET Core 3.0+ 内置)和 Newtonsoft.Json(第三方库,功能更丰富)。
使用 System.Text.Json(推荐,轻量且高效)
System.Text.Json 是 .NET 官方推出的 JSON 处理库,无需额外安装,性能优异,适合大多数场景。
(1)基础步骤
- 创建 C# 对象:定义需要序列化的类(属性需与 JSON 字段对应)。
- 序列化对象为 JSON 字符串:使用
JsonSerializer.Serialize()方法。 - 写入文件:通过
File.WriteAllText()或File.WriteAllTextAsync()将 JSON 字符串保存到文件。
(2)代码示例
using System;
using System.Text.Json;
using System.IO;
// 1. 定义需要序列化的类
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string[] Hobbies { get; set; }
}
class Program
{
static void Main()
{
// 2. 创建对象并赋值
var user = new User
{
Id = 1,
Name = "张三",
Age = 25,
Hobbies = new[] { "阅读", "编程", "旅行" }
};
// 3. 序列化为 JSON 字符串(格式化缩进,便于阅读)
string jsonString = JsonSerializer.Serialize(user, new JsonSerializerOptions
{
WriteIndented = true, // 启用缩进格式化
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 允许非 ASCII 字符(如中文)不转义
});
// 4. 写入 JSON 文件(路径可自定义)
string filePath = "user.json";
File.WriteAllText(filePath, jsonString);
Console.WriteLine("JSON 文件保存成功!路径:" + filePath);
}
}
(3)执行结果
生成的 user.json 文件内容如下:
{
"Id": 1,
"Name": "张三",
"Age": 25,
"Hobbies": [
"阅读",
"编程",
"旅行"
]
}
使用 Newtonsoft.Json(功能更全面,适用于复杂场景)
Newtonsoft.Json(又称 Json.NET)是老牌 JSON 库,支持更多高级功能(如自定义序列化规则、忽略空值、日期格式化等),需先通过 NuGet 安装:
Install-Package Newtonsoft.Json
(1)代码示例
using Newtonsoft.Json;
using System;
// User 类定义同上
class Program
{
static void Main()
{
var user = new User
{
Id = 1,
Name = "李四",
Age = 30,
Hobbies = new[] { "游戏", "音乐" }
};
// 序列化为 JSON(Newtonsoft.Json 默认支持缩进格式化)
string jsonString = JsonConvert.SerializeObject(user, Formatting.Indented);
// 写入文件
string filePath = "user_newtonsoft.json";
File.WriteAllText(filePath, jsonString);
Console.WriteLine("JSON 文件保存成功!(Newtonsoft.Json)路径:" + filePath);
}
}
(2)特点对比
| 特性 | System.Text.Json |
Newtonsoft.Json |
|---|---|---|
| 安装方式 | .NET 内置,无需安装 | 需通过 NuGet 安装 |
| 性能 | 更快(底层优化) | 略慢,但功能更灵活 |
| 功能丰富度 | 基础功能完善 | 支持自定义序列化、LINQ 查询等 |
| 日期格式化 | 需手动配置 | 默认支持多种日期格式 |
| 非 ASCII 字符处理 | 默认转义,需配置不转义 | 默认保留非 ASCII 字符 |
如何打开 JSON 文件(读取并反序列化)
打开 JSON 文件的核心是反序列化(Deserialization),即将 JSON 字符串转换为 C# 对象,与序列化类似,System.Text.Json 和 Newtonsoft.Json 均提供相应方法。
使用 System.Text.Json 读取 JSON 文件
(1)基础步骤
- 读取 JSON 文件内容:使用
File.ReadAllText()或File.ReadAllTextAsync()获取 JSON 字符串。 - 反序列化为 C# 对象:使用
JsonSerializer.Deserialize<T>()方法(T为目标类型)。
(2)代码示例
using System;
using System.Text.Json;
using System.IO;
// User 类定义同上
class Program
{
static void Main()
{
string filePath = "user.json"; // 确保文件存在
try
{
// 1. 读取 JSON 文件内容
string jsonString = File.ReadAllText(filePath);
// 2. 反序列化为 User 对象
User user = JsonSerializer.Deserialize<User>(jsonString);
// 3. 输出对象属性
Console.WriteLine("读取 JSON 文件成功!");
Console.WriteLine($"ID: {user.Id}");
Console.WriteLine($"姓名: {user.Name}");
Console.WriteLine($"年龄: {user.Age}");
Console.WriteLine($"爱好: {string.Join(", ", user.Hobbies)}");
}
catch (FileNotFoundException)
{
Console.WriteLine($"错误:文件 {filePath} 不存在!");
}
catch (JsonException)
{
Console.WriteLine($"错误:文件 {filePath} 格式不正确,无法解析为 JSON!");
}
}
}
(3)执行结果
若 user.json 文件存在且格式正确,输出如下:
读取 JSON 文件成功!
ID: 1
姓名: 张三
年龄: 25
爱好: 阅读, 编程, 旅行
使用 Newtonsoft.Json 读取 JSON 文件
(1)代码示例
using Newtonsoft.Json;
using System;
using System.IO;
// User 类定义同上
class Program
{
static void Main()
{
string filePath = "user_newtonsoft.json";
try
{
// 1. 读取 JSON 文件内容
string jsonString = File.ReadAllText(filePath);
// 2. 反序列化为 User 对象
User user = JsonConvert.DeserializeObject<User>(jsonString);
// 3. 输出对象属性
Console.WriteLine("读取 JSON 文件成功!(Newtonsoft.Json)");
Console.WriteLine($"ID: {user.Id}");
Console.WriteLine($"姓名: {user.Name}");
Console.WriteLine($"年龄: {user.Age}");
Console.WriteLine($"爱好: {string.Join(", ", user.Hobbies)}");
}
catch (FileNotFoundException)
{
Console.WriteLine($"错误:文件 {filePath} 不存在!");
}
catch (JsonException)
{
Console.WriteLine($"错误:文件 {filePath} 格式不正确,无法解析为 JSON!");
}
}
}
异常处理注意事项
读取 JSON 文件时,需处理常见异常:
FileNotFoundException:文件路径错误或文件不存在。JsonException:JSON 格式错误(如缺少引号、逗号、大括号不匹配等)。UnauthorizedAccessException:无文件读写权限(需确保程序对目标路径有访问权限)。
进阶技巧与注意事项
处理复杂对象(嵌套对象、集合)
JSON 数据包含嵌套对象或集合,只需在 C# 类中定义对应的嵌套类或集合属性即可。
{
"Id": 1,
"Name": "王五",
"Address": {
"City": "北京",
"Street": "朝阳区建国路"
},
"Orders": [
{ "OrderId": "A001", "Amount": 100 },
{ "OrderId": "A002", "Amount": 200 }
]
}
对应的 C# 类:
public class Address
{
public string City { get; set; }
public string Street { get; set; }


还没有评论,来说两句吧...