Skip to main content

How to Build a JSON Object in Code with JsonObject in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Sometimes you need a piece of JSON whose shape you decide as you go, and writing a class for it would be overkill. In C#, JsonObject from System.Text.Json.Nodes is a JSON object you build in code: add properties by name, change them, read them back, and print the JSON.

Syntax​

Syntax
using System.Text.Json.Nodes;

JsonObject <name> = new()
{
["<property>"] = <value>,
};

<name>["<property>"] = <value>;
PartWhat it does
new() { ["<property>"] = <value>, }Creates the object with its first properties
<name>["<property>"] = <value>Adds the property, or replaces its value when it's already there
<value>A string, a number, true or false, or another JSON node

Microsoft's JsonObject reference describes the class in one line: "Represents a mutable JSON object." Its guide to the JSON DOM adds: "JsonNode and the classes that derive from it in the System.Text.Json.Nodes namespace provide the ability to create a mutable DOM."

The Example​

The program builds a person with a name, an age and an admin flag, then adds a city and changes the age. It prints the whole object, one property, and the number of properties.

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 creates a JsonObject person with name Ana, age 31 and isAdmin false, sets city to Lisbon and age to 32, then prints the person, the name property and the Count.

main.cs
using System.Text.Json.Nodes;

JsonObject person = new()
{
["name"] = "Ana",
["age"] = 31,
["isAdmin"] = false,
};

person["city"] = "Lisbon";
person["age"] = 32;

Console.WriteLine(person);
Console.WriteLine(person["name"]);
Console.WriteLine(person.Count);

Step 2: Run It​

Terminal
dotnet run main.cs
Output
{
"name": "Ana",
"age": 32,
"isAdmin": false,
"city": "Lisbon"
}
Ana
4

A zsh terminal where dotnet run main.cs prints the JSON object with name Ana, age 32, isAdmin false and city Lisbon, then Ana and 4.

  1. Printing the object gave indented JSON, with the properties in the order they were added.
  2. city was new, so it was added at the end. age was already there, so its value changed from 31 to 32 in place.
  3. person["name"] gave the value, Ana, and Count the number of properties, 4.

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

Property Names Are Case-Sensitive​

name and Name are different properties:

main.cs
using System.Text.Json.Nodes;

JsonObject person = new() { ["name"] = "Ana" };

Console.WriteLine(person["name"] is null);
Console.WriteLine(person["Name"] is null);
Console.WriteLine(person.ContainsKey("Name"));
Output
False
True
False

Reading a property that isn't there gives null rather than an error, so a wrong case shows up as a missing value.

Add Throws for an Existing Property​

Add only adds. For a name that's already there, it throws, where the square brackets would have replaced the value:

main.cs
using System.Text.Json.Nodes;

JsonObject person = new() { ["name"] = "Ana" };
person.Add("name", "Ben");
Output
Unhandled exception. System.ArgumentException: An item with the same key has already been added. Key: name (Parameter 'key')
at System.Collections.ThrowHelper.ThrowDuplicateKey[TKey](TKey key)
at System.Collections.Generic.OrderedDictionary`2.TryInsert(Int32 index, TKey key, TValue value, InsertionBehavior behavior, Int32& keyIndex)
at System.Collections.Generic.OrderedDictionary`2.Add(TKey key, TValue value)
at System.Text.Json.Nodes.JsonObject.Add(String propertyName, JsonNode value)
at Program.<Main>$(String[] args) in /Users/you/demo/main.cs:line 4

Common Mistakes​

MistakeWhat happensDo this instead
Reading person["Name"] for a property called namenull, as if it were missingUse the exact name
Calling Add for a property that may existArgumentException: An item with the same key has already been added. Key: name (Parameter 'key')Set it with person["name"] = ...
Forgetting using System.Text.Json.Nodes;error CS0246: The type or namespace name 'JsonObject' could not be foundAdd the using line at the top

Troubleshooting​

SymptomLikely causeFix
A property reads as nullThe name or its case doesn't matchCheck the name, or ContainsKey it
ArgumentException ... Key: nameAdd met an existing propertyUse the square brackets to replace

FAQ​

How do I remove a property?​

person.Remove("city") removes it and returns True. A second Remove("city") returned False, and the JSON was left with {"name":"Ana"}.

How do I get the JSON as a string?​

person.ToJsonString() returns it on one line, as in the output above after the removal. Printing the object, as in Step 1, gives the indented form.

Conclusion​

JsonObject builds JSON in code: create it with new() { ["name"] = value }, set properties with obj["name"] = value, which adds or replaces, and read them the same way. Names are case-sensitive, and Add throws for a name that's already there.

Additional Resources​