我有list JSON字符串,我想将它们合并到一个JSON数组中。
我从API中得到一个结果,需要迭代结果字符串才能得到一个结果字符串。
我有一个列表字符串,我需要迭代它,并将列表字符串转换为一个包含一个根元素的字符串,并将其中的结果合并。
using Newtonsoft.Json;
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}");
foreach (var eachJson in jsonResult)
{
//Wat to merge JSON string
}
//Result should be with one root "arrayResult" and with in that the result array merged
}
}
}
**Result**
*Input*
- 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"
}
]
}
*Output*
- Merged string with one root
{
"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"
}
]
}
发布于 2022-08-15 22:45:22
解决方案1: LINQ方法
jsonResult
列表中,将每个项(JSON )解析为JObject
。arrayResult
作为JToken
的值。它将arrayResult
数组中的项作为List<JToken>
返回。arrayResult
属性的对象,该属性保存来自2的结果。using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
List<JToken> items = jsonResult.Select(x => JObject.Parse(x))
.SelectMany(x => x["arrayResult"])
.ToList();
dynamic result = new {
arrayResult = items
};
foreach
解决方案2: 循环方法
arrayResult
属性的对象,该属性包含数组。jsonResult
中的每个元素,将JSON字符串解析为JObject
,从JObject
中提取arrayResult
值。这将返回项目列表。然后需要.AddRange()
将项目列表添加到result.arrayResult
中。dynamic result = new {
arrayResult = new List<dynamic>()
};
foreach (var eachJson in jsonResult)
{
result.arrayResult.AddRange(JObject.Parse(eachJson)
.SelectToken("arrayResult")
.ToList());
}
https://stackoverflow.com/questions/73369637
复制