如何将多个含arrayResult的JSON字符串合并为单个JSON数组?
使用Newtonsoft.Json合并多个含arrayResult根数组的JSON字符串
完整实现代码
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace ConsoleApp5 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); MergeJsonResult(); } private static void MergeJsonResult() { List<string> jsonResult = new List<string>(); jsonResult.Add("{\n \"arrayResult\": [\n {\"Item1\": \"123\",\n \"Item2\": \"858\",\n \"Item3\": \"789\"\n },\n {\"Item1\": \"2588\",\n \"Item2\": \"858\",\n \"Item3\": \"587\"\n }\n ]\n}"); jsonResult.Add("{\n \"arrayResult\": [\n {\"Item1\": \"123\",\n \"Item2\": \"858\",\n \"Item3\": \"789\"\n },\n {\"Item1\": \"2588\",\n \"Item2\": \"858\",\n \"Item3\": \"587\"\n }\n ]\n}"); jsonResult.Add("{\n \"arrayResult\": [\n {\"Item1\": \"123\",\n \"Item2\": \"858\",\n \"Item3\": \"789\"\n },\n {\"Item1\": \"2588\",\n \"Item2\": \"858\",\n \"Item3\": \"587\"\n }\n ]\n}"); // 初始化存储所有合并元素的数组 JArray mergedArray = new JArray(); foreach (var eachJson in jsonResult) { // 解析单个JSON字符串为JObject JObject jsonObj = JObject.Parse(eachJson); // 取出当前JSON中的arrayResult数组 JArray currentArray = (JArray)jsonObj["arrayResult"]; // 将当前数组的所有元素添加到合并数组中 mergedArray.Merge(currentArray); } // 创建最终的根JSON对象 JObject finalResult = new JObject(); finalResult["arrayResult"] = mergedArray; // 序列化为格式化的JSON字符串并输出 string mergedJson = finalResult.ToString(Formatting.Indented); Console.WriteLine(mergedJson); } } }
实现说明
- 借助LINQ to JSON API:用
JObject和JArray直接操作JSON结构,无需定义实体类,适配动态JSON格式场景。 - 遍历解析与合并:逐个解析输入的JSON字符串,提取每个字符串里的
arrayResult数组,通过Merge方法批量将子数组元素合并到总数组中,也可以用循环逐个添加元素(mergedArray.Add(item))。 - 生成最终JSON:创建根对象并将合并后的数组赋值给
arrayResult键,最后序列化为带缩进的格式化JSON字符串。
输入示例
- String1
{ "arrayResult": [ { "Item1": "123", "Item2": "858", "Item3": "789" }, { "Item1": "2588", "Item2": "858", "Item3": "587" } ] }
- String2
{ "arrayResult": [ { "Item1": "123", "Item2": "858", "Item3": "789" }, { "Item1": "2588", "Item2": "858", "Item3": "587" } ] }
- String3
{ "arrayResult": [ { "Item1": "123", "Item2": "858", "Item3": "789" }, { "Item1": "2588", "Item2": "858", "Item3": "587" } ] }
输出结果
{ "arrayResult": [ { "Item1": "123", "Item2": "858", "Item3": "789" }, { "Item1": "2588", "Item2": "858", "Item3": "587" }, { "Item1": "123", "Item2": "858", "Item3": "789" }, { "Item1": "2588", "Item2": "858", "Item3": "587" }, { "Item1": "123", "Item2": "858", "Item3": "789" }, { "Item1": "2588", "Item2": "858", "Item3": "587" } ] }
内容的提问来源于stack exchange,提问作者Rupesh
相关产品推荐
相关产品推荐

