如何使用Newtonsoft.Json将多个JSON数组合并为单个统一JSON数组?
如何使用Newtonsoft.Json将多个JSON数组合并为扁平化的单个数组
我在某文件路径下存有多个JSON数组文件,示例如下:
JSON1:
[ { "name": "name1", "salary": 65000 }, { "name": "name2", "salary": 68000 } ]
JSON2:
[ { "name": "name3", "salary": 56000 }, { "name": "name4", "salary": 58000 } ]
JSON3:
[ { "name": "name5", "salary": 76000 }, { "name": "name6", "salary": 78000 } ]
JSON4:
[ { "name": "name7", "salary": 86000 }, { "name": "name8", "salary": 88000 } ]
我原本使用以下C#代码尝试合并:
// List to store all the json objects List<object> combinedJsonObjects = new List<object>(); // Load and append the JSON files foreach (string filePath in jsonFilePaths) { string jsonContent = File.ReadAllText(filePath); object jsonObject = JsonConvert.DeserializeObject(jsonContent); combinedJsonObjects.Add(jsonObject); } // Serialize the appended JSON objects string combinedJson = JsonConvert.SerializeObject(combinedJsonObjects, Newtonsoft.Json.Formatting.Indented); // save JSON file string combinedJsonFilePath = @"C:\filePath\new.json"; File.WriteAllText(combinedJsonFilePath, combinedJson);
运行后得到的是嵌套数组结构,但我需要所有对象处于同一数组的扁平化结构,请问该如何修改代码?
解决方案
问题核心是你把每个完整的JSON数组作为单个元素添加到了合并列表中,最终序列化自然形成嵌套数组。要实现扁平化合并,需要提取每个JSON数组中的元素,逐个添加到合并列表,而非添加整个数组。
方案1:定义实体类(类型安全推荐)
创建对应JSON结构的实体类,反序列化为强类型数组后批量添加元素:
// 匹配JSON对象结构的实体类 public class Employee { public string name { get; set; } public int salary { get; set; } } // 存储所有扁平化后的对象 List<Employee> combinedEmployees = new List<Employee>(); foreach (string filePath in jsonFilePaths) { string jsonContent = File.ReadAllText(filePath); // 反序列化为Employee数组 Employee[] employees = JsonConvert.DeserializeObject<Employee[]>(jsonContent); // 将数组中所有元素添加到合并列表 combinedEmployees.AddRange(employees); } // 序列化为扁平化JSON数组 string combinedJson = JsonConvert.SerializeObject(combinedEmployees, Newtonsoft.Json.Formatting.Indented); // 保存文件 string combinedJsonFilePath = @"C:\filePath\new.json"; File.WriteAllText(combinedJsonFilePath, combinedJson);
方案2:动态处理(无需实体类)
如果不想定义实体类,可使用JArray解析并遍历元素:
List<JObject> combinedObjects = new List<JObject>(); foreach (string filePath in jsonFilePaths) { string jsonContent = File.ReadAllText(filePath); JArray jsonArray = JArray.Parse(jsonContent); // 遍历数组中的每个对象并添加到合并列表 foreach (JObject obj in jsonArray) { combinedObjects.Add(obj); } } string combinedJson = JsonConvert.SerializeObject(combinedObjects, Newtonsoft.Json.Formatting.Indented); File.WriteAllText(@"C:\filePath\new.json", combinedJson);
说明
- 方案1类型安全,便于后续数据操作,适合结构固定的场景;
- 方案2灵活性高,适合临时处理或JSON结构不确定的场景,但缺少编译时类型检查。
内容的提问来源于stack exchange,提问作者paone
相关产品推荐
相关产品推荐

