目录
[JSON 序列化封装](#JSON 序列化封装)
简介
采用依赖抽象与实现分离的设计模式,核心是对第三方库进行封装与适配。
设计特点
接口隔离:每个模块都以 Impl 结尾的文件作为具体实现,上层业务只需依赖抽象接口,不直接依赖第三方库。
可替换性:如果未来需要更换 JSON / 日志 / YAML 库(比如从 Newtonsoft.Json 切换到 System.Text.Json),只需替换 Impl 实现,无需修改业务代码。
依赖管理:每个模块都有独立的 依赖项 节点,便于版本控制和冲突排查。
文件 / 内存双模式:NewtonJson 和 YamlDotNet 都提供了文件操作与内存操作两种实现,适配不同场景需求。
实战案例
JSON 序列化封装
- NewtonJsonImpl.cs(内存操作实现)
-
Serialize(object): string:将对象序列化为 JSON 字符串
-
Deserialize(string): T:将 JSON 字符串反序列化为指定类型对象
public interface ICxJson
{
///
/// 对象序列化为 JSON 字符串
///
string Serialize(object obj);/// <summary> /// JSON 字符串反序列化为对象 /// </summary> T Deserialize<T>(string json) where T : class;}
-
内存序列化
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class NewtonJsonImpl : ICxJson
{
// 全局复用序列化器,提升性能
private static readonly JsonSerializer _serializer;
static NewtonJsonImpl()
{
_serializer = new JsonSerializer
{
// 格式化缩进
Formatting = Formatting.Indented,
// 忽略空值
NullValueHandling = NullValueHandling.Ignore
};
// 枚举 → 字符串
_serializer.Converters.Add(new StringEnumConverter());
}
public string Serialize(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
using var sw = new StringWriter();
_serializer.Serialize(sw, obj);
return sw.ToString();
}
public T Deserialize<T>(string json) where T : class
{
if (string.IsNullOrWhiteSpace(json))
throw new ArgumentException("JSON 字符串不能为空");
using var sr = new StringReader(json);
return _serializer.Deserialize(sr, typeof(T)) as T;
}
}
文件序列化
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class NewtonJsonFileImpl : ICxJsonFile
{
private static readonly JsonSerializer _serializer;
static NewtonJsonFileImpl()
{
_serializer = new JsonSerializer
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
};
_serializer.Converters.Add(new StringEnumConverter());
}
public void Serialize(object obj, string filePath)
{
if (obj == null) throw new ArgumentNullException(nameof(obj));
if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException("文件路径不能为空");
try
{
using var fs = File.CreateText(filePath);
_serializer.Serialize(fs, obj);
}
catch (Exception ex)
{
throw new InvalidOperationException($"JSON 写入文件失败:{filePath}", ex);
}
}
public T Deserialize<T>(string filePath) where T : class
{
if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException("文件路径不能为空");
if (!File.Exists(filePath)) throw new FileNotFoundException("文件不存在", filePath);
try
{
using var fs = File.OpenText(filePath);
return _serializer.Deserialize(fs, typeof(T)) as T;
}
catch (Exception ex)
{
throw new InvalidOperationException($"JSON 读取文件失败:{filePath}", ex);
}
}
}
使用例子
// 1. 内存操作
ICxJson json = new NewtonJsonImpl();
string jsonStr = json.Serialize(new User { Id = 1, Name = "张三" });
User user = json.Deserialize<User>(jsonStr);
// 2. 文件操作
ICxJsonFile jsonFile = new NewtonJsonFileImpl();
jsonFile.Serialize(user, "user.json");
User userFromFile = jsonFile.Deserialize<User>("user.json");
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
NewtonJsonFileImpl.cs((文件操作实现)
- Serialize(object, string): void:将对象序列化为 JSON 并写入指定文件
- Deserialize(string): T:从指定文件读取 JSON 并反序列化为指定类型对象
使用案例
using System;
using System.IO;
using CxBaseSupply;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace CxDepends
{
/// <summary>
/// Newtonsoft.Json 文件操作实现类
/// 实现 ICxJsonFile 接口:对象 ↔ JSON 文件
/// </summary>
public class NewtonJsonFileImpl : ICxJsonFile
{
/// <summary>
/// 静态全局序列化器(全局复用,提升性能)
/// </summary>
private static readonly JsonSerializer _jsonSerializer;
/// <summary>
/// 静态构造:一次性配置序列化规则
/// </summary>
static NewtonJsonFileImpl()
{
_jsonSerializer = new JsonSerializer();
// 枚举 → 字符串(不转数字)
_jsonSerializer.Converters.Add(new StringEnumConverter());
// 格式化缩进(文件可读性更强)
_jsonSerializer.Formatting = Formatting.Indented;
// 忽略空值属性
_jsonSerializer.NullValueHandling = NullValueHandling.Ignore;
}
/// <summary>
/// 将对象序列化为 JSON 并写入文件
/// </summary>
/// <param name="obj">要序列化的对象</param>
/// <param name="file">文件路径</param>
public void Serialize(object obj, string file)
{
// 参数校验
if (obj == null)
throw new ArgumentNullException(nameof(obj), "序列化对象不能为空");
if (string.IsNullOrWhiteSpace(file))
throw new ArgumentException("文件路径不能为空", nameof(file));
try
{
// 创建文件流,using 自动释放
using (StreamWriter sw = File.CreateText(file))
{
_jsonSerializer.Serialize(sw, obj);
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"JSON 写入文件失败:{file}", ex);
}
}
/// <summary>
/// 从文件读取 JSON 并反序列化为对象
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="file">文件路径</param>
/// <returns>强类型对象</returns>
public T Deserialize<T>(string file) where T : class
{
// 参数校验
if (string.IsNullOrWhiteSpace(file))
throw new ArgumentException("文件路径不能为空", nameof(file));
if (!File.Exists(file))
throw new FileNotFoundException("JSON 文件不存在", file);
try
{
using (StreamReader sr = File.OpenText(file))
{
return _jsonSerializer.Deserialize(sr, typeof(T)) as T;
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"JSON 反序列化失败:{file}", ex);
}
}
}
}
总结
一句话记住所有依赖作用
- Newtonsoft.Json = 操作 JSON
- Serilog = 记录日志
- YamlDotNet = 操作 YAML