You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 无需使用File.ReadAllLines读写JSON文件序列化对象集合的方法

C# Customer对象集合JSON序列化与反序列化方案

1. 列表序列化写入文件的简化实现

你当前逐对象序列化直接写入的方式会生成拼接的非标准JSON结构,后续解析难度大,推荐以下两种规范实现:

方案A:存储为标准JSON数组(最常用)

直接将整个List<Customer>作为序列化输入,一次性生成标准JSON数组结构,无需手动管理文件流:

// System.Text.Json 实现
using System.Text.Json;

// 序列化整个列表,WriteIndented可配置是否格式化输出
string jsonResult = JsonSerializer.Serialize(list, new JsonSerializerOptions { WriteIndented = true });
// 直接写入文件
File.WriteAllText("customers.json", jsonResult);

如果使用Newtonsoft.Json,写法逻辑一致:

using Newtonsoft.Json;

string jsonResult = JsonConvert.SerializeObject(list, Formatting.Indented);
File.WriteAllText("customers.json", jsonResult);

方案B:存储为JSON Lines格式(每行一个对象)

如果业务需要每行存一个独立的Customer JSON对象,可直接用File.WriteAllLines简化操作:

var jsonLines = list.Select(cust => JsonSerializer.Serialize(cust));
File.WriteAllLines("customers.jsonl", jsonLines);

2. 读取文件反序列化的简化实现

对应上面两种存储格式,分别有对应的极简实现,无需手动拆分字符串或使用正则:

对应方案A的标准JSON数组读取

直接读取全量文件内容,反序列化为List<Customer>即可:

// System.Text.Json 实现
string jsonContent = File.ReadAllText("customers.json");
List<Customer> customerList = JsonSerializer.Deserialize<List<Customer>>(jsonContent);

// Newtonsoft.Json 实现
// List<Customer> customerList = JsonConvert.DeserializeObject<List<Customer>>(jsonContent);

对应方案B的JSON Lines格式读取

直接按行读取,逐行反序列化后合并为列表:

List<Customer> customerList = File.ReadAllLines("customers.jsonl")
    .Where(line => !string.IsNullOrWhiteSpace(line)) // 过滤空行
    .Select(line => JsonSerializer.Deserialize<Customer>(line))
    .ToList();

补充说明

你原有实现的核心问题是序列化时没有添加任何分隔符,输出的是{"FirstName":"xxx"}{"FirstName":"yyy"}这类非标准拼接内容,既不符合JSON规范,也会大幅提升后续解析成本,不推荐使用。

内容的提问来源于stack exchange,提问作者Peteros527

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 04:54:04