Skip to main content

How to Build a JSON Array in Code with JsonArray in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

A JSON array is a list in square brackets, and in C# you can build one item by item with JsonArray from System.Text.Json.Nodes. Start it with a few items, Add more as the program runs, then read them back or turn the whole array into JSON text.

Syntax​

Syntax
using System.Text.Json.Nodes;

JsonArray <name> = new() { <item>, <item> };
<name>.Add(<item>);

JsonNode? <first> = <name>[0];
int <count> = <name>.Count;
PartWhat it does
new() { <item>, <item> }Creates the array with its first items
<name>.Add(<item>)Adds an item at the end
<item>A string, a number, true or false, or another JSON node, such as a JsonObject
<name>[0], <name>.CountReads an item by position, from 0, and counts the items

Microsoft's JsonArray reference describes the class in one line: "Represents a mutable JSON array."

The Example​

The program builds an array of colors, adds one, and reads it back. Then it builds a second array that mixes a number, a string, a true and a small object, which JSON allows.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which starts with the line # PublishAot=false, creates a JsonArray colors with red and green, adds blue, prints the Count, the first item and the array as JSON, then creates a JsonArray mixed with 1, two, true and an object with three set to 3, and prints it as JSON.

main.cs
#:property PublishAot=false

using System.Text.Json.Nodes;

JsonArray colors = new() { "red", "green" };
colors.Add("blue");

Console.WriteLine(colors.Count);
Console.WriteLine(colors[0]);
Console.WriteLine(colors.ToJsonString());

JsonArray mixed = new() { 1, "two", true, new JsonObject { ["three"] = 3 } };
Console.WriteLine(mixed.ToJsonString());

Step 2: Run It​

Terminal
dotnet run main.cs
Output
3
red
["red","green","blue"]
[1,"two",true,{"three":3}]

A zsh terminal where dotnet run main.cs prints 3, red, the array red, green, blue as JSON, and the array 1, two, true and an object with three set to 3.

  1. Two items from the braces and one from Add make 3, in that order.
  2. colors[0] is the first item, red.
  3. The second array kept each item's JSON type: a number, a string in quotes, true, and an object.

The command is the same in zsh, bash and PowerShell.

One Node, One Parent​

A node can only be in one place. Adding the same object to a second array throws:

main.cs
#:property PublishAot=false

using System.Text.Json.Nodes;

JsonObject tag = new() { ["name"] = "urgent" };

JsonArray first = new() { tag };
JsonArray second = new() { tag };
Output
Unhandled exception. System.InvalidOperationException: The node already has a parent.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_NodeAlreadyHasParent()
at System.Text.Json.Nodes.JsonNode.AssignParent(JsonNode parent)
at System.Text.Json.Nodes.JsonArray.Add[T](T value)
at Program.<Main>$(String[] args) in /Users/you/demo/main.cs:line 8

Give the second array a copy, with DeepClone():

main.cs
#:property PublishAot=false

using System.Text.Json.Nodes;

JsonObject tag = new() { ["name"] = "urgent" };

JsonArray first = new() { tag };
JsonArray second = new() { tag.DeepClone() };

Console.WriteLine(first.ToJsonString());
Console.WriteLine(second.ToJsonString());
Output
[{"name":"urgent"}]
[{"name":"urgent"}]

Common Mistakes​

MistakeWhat happensDo this instead
Adding one node to two arraysInvalidOperationException: The node already has a parent.Add node.DeepClone() to the second one
Leaving out the first line in a one-file programNotSupportedException: JsonTypeInfo metadata for type 'System.String' was not provided by TypeInfoResolver ...Start the file with #:property PublishAot=false
Reading one past the last item, such as mixed[4] in a 4-item arrayArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')Positions start at 0: the last item is mixed[mixed.Count - 1]

Troubleshooting​

SymptomLikely causeFix
The node already has a parent.The node was already in another array or objectUse DeepClone()
JsonTypeInfo metadata for type 'System.String' was not provided by TypeInfoResolver of type '...EmptyJsonTypeInfoResolver'A one-file program with native AOT onThe fix

FAQ​

Can one JsonArray hold different types?​

Yes. JSON allows it, and the mixed array in Step 1 held a number, a string, true and an object.

What does an item come back as?​

A JsonNode?. Printing it gives its value, as red showed. For an object in the array, read its properties by name: mixed[3]!["three"] printed 3. The ! tells C# that the item isn't null.

Conclusion​

JsonArray builds a JSON array in code: start it with new() { ... }, Add more, read items by position and count them with Count. A node can belong to one array or object only, so add a DeepClone() to a second one, and in a one-file program start with #:property PublishAot=false.

Additional Resources​