I have list JSON string, I want to merge them into a single JSON array.
I am getting a result from an API and need to iterate the result string to get one single result string
I have a list string and I need to iterate it and convert the list string into a single string with one root element and result merged with in it
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"
}
]
}
Solution 1: LINQ approach
In
jsonResultlist, parse each item (JSON string) toJObject.From result 1, extract the value of
arrayResultasJToken. It returns the items inarrayResultarray asList<JToken>.Create an object with
arrayResultproperty which holds the result from 2.Demo Solution 1 @ .NET Fiddle
Solution 2:
foreachloop approachCreate an object with
arrayResultproperty which holds the array.Iterate each element in
jsonResult, parse JSON string toJObject, extract thearrayResultvalue fromJObject. This returns list of items. Then you need to.AddRange()to add the items list toresult.arrayResult.Demo Solution 2 @ .NET Fiddle