This is one way of converting a JSON array of any JSON objects into batches. This function uses the LINQ Chunk method to convert a 1 dimensional array input into a 2 dimensional array output:
Example input array:
[
{ "a": "1" },
{ "a": "2" },
{ "a": "3" },
{ "a": "4" },
{ "a": "5" },
{ "a": "6" },
{ "a": "7" }
]
Converted into batches of 3:
[
[
{"a":"1"},
{"a":"2"},
{"a":"3"}
],
[
{"a":"4"},
{"a":"5"},
{"a":"6"}
],
[
{"a":"7"}
]
]
THE CODE:
using System;
using System.Collections.Generic;
using System.Linq;
// For demo purpose: Grab a Json array and convert it into an array of objects
string jsonInputString = "[ { \"a\": \"1\" }, { \"a\": \"2\" }, { \"a\": \"3\" }, { \"a\": \"4\" }, { \"a\": \"5\" }, { \"a\": \"6\" }, { \"a\": \"7\" } ]";
List<object> jsonInput = System.Text.Json.JsonSerializer.Deserialize<List<object>>(jsonInputString);
// Create a new list of objects, and use the Chunk method to create batches
// of a certain size
List<object> batch = new List<object>();
foreach (var chunk in jsonInput.Chunk(3))
{
batch.Add(chunk);
}
// For demo purposes, convert the batched objects as a Json string
string jsonOutputString = System.Text.Json.JsonSerializer.Serialize(batch);
// Output the contents
Console.WriteLine(jsonOutputString);
When using the Chunk method, C# does the heavy lifting of breaking the array into batches of a maximum size.
MORE TO READ:
- Enumerable.Chunk<TSource>(IEnumerable<TSource>, Int32) Method from Microsoft
- Streamlining Collection Chunking in .NET 6: .Chunk vs. Methods by Jitendra Mesavaniya
- C# Sort JArray NewtonSoft.Json from briancaos
- C# Use HttpClient to GET JSON from API endpoint from briancaos
- C# HttpClient POST or PUT Json with content type application/json from briancaos