如何使用ChoETL将含嵌套数组的JSON转换为CSV
使用ChoETL将带嵌套数组的JSON转换为指定格式CSV
核心需求实现步骤
针对字段重命名、数组值拼接成字符串的需求,可通过ChoETL的Map方法结合LINQ表达式快速实现,以下是具体方案:
1. 定义C#实体类(示例)
假设你的JSON对应的实体类结构如下(可替换为你实际的类):
public class Employer { public string Name { get; set; } } public class Person { public string Id { get; set; } public string FullName { get; set; } public List<Employer> PreviousEmployers { get; set; } }
2. 配置ChoETL转换逻辑
场景1:从已反序列化的实体列表生成CSV
using ChoETL; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // 模拟从JSON反序列化得到的实体集合 var persons = new List<Person> { new Person { Id = "P001", FullName = "John Doe", PreviousEmployers = new List<Employer> { new Employer { Name = "Company A" }, new Employer { Name = "Company B" }, new Employer { Name = "Company C" } } }, new Person { Id = "P002", FullName = "Jane Smith", PreviousEmployers = new List<Employer> { new Employer { Name = "Company X" } } } }; // 生成目标CSV using (var writer = new ChoCSVWriter("output.csv") .WithFirstLineHeader() // 字段重命名:将原Id映射为CSV的PersonId,FullName映射为EmployeeName .Map("PersonId", p => p.Id) .Map("EmployeeName", p => p.FullName) // 数组拼接:将PreviousEmployers的Name用+拼接,并重命名为EmployerName2 .Map("EmployerName2", p => string.Join("+", p.PreviousEmployers?.Select(e => e.Name) ?? Enumerable.Empty<string>()))) { writer.Write(persons); } } }
场景2:直接从JSON文件读取并转换CSV
无需先反序列化实体,可直接结合ChoJSONReader和ChoCSVWriter:
using ChoETL; using System.Linq; class Program { static void Main(string[] args) { using (var reader = new ChoJSONReader<Person>("input.json")) using (var writer = new ChoCSVWriter("output.csv") .WithFirstLineHeader() .Map("PersonId", p => p.Id) .Map("EmployeeName", p => p.FullName) .Map("EmployerName2", p => string.Join("+", p.PreviousEmployers?.Select(e => e.Name) ?? Enumerable.Empty<string>()))) { writer.Write(reader); } } }
关键配置说明
- 字段重命名:通过
.Map("CSV目标字段名", 实体字段表达式)实现,将C#类的字段映射为CSV中你需要的名称。 - 数组值拼接:在
Map的表达式中,使用string.Join("+", ...)遍历嵌套数组,提取目标属性值并拼接为字符串;加入?? Enumerable.Empty<string>()可避免数组为空时的空引用异常。 - 特殊处理:如果数组元素包含分隔符(如
+),可提前对值做清洗,例如e.Name.Replace("+", "_"),防止CSV解析出错。
内容的提问来源于stack exchange,提问作者Charline
相关产品推荐
相关产品推荐

