Skip to main content

How to Turn a JsonNode into a JSON String with ToJsonString in C#

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

Once you've built JSON in C# with JsonObject or JsonArray, you need it as text: to send, to save, or to print. ToJsonString() gives you exactly that JSON, on one line, or indented when you ask for it.

Syntax​

Syntax
string <json> = <node>.ToJsonString();
string <json> = <node>.ToJsonString(new JsonSerializerOptions { WriteIndented = true });
PartWhat it does
<node>Any JsonNode: a JsonObject, a JsonArray or a single value
ToJsonString()Returns the JSON on one line, with no spaces between the parts
new JsonSerializerOptions { WriteIndented = true }Asks for indented JSON instead, one property per line. Needs using System.Text.Json;

Microsoft's ToJsonString reference: "Converts the current instance to a string in JSON format." It returns "The JSON representation of the current instance."

The Example​

The program builds a small tea order as a JsonObject and turns it into text three ways: ToJsonString(), ToJsonString with indenting, and ToString().

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 order with item Tea and qty 2, then prints order.ToJsonString(), order.ToJsonString with WriteIndented set to true, and order.ToString().

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

JsonObject order = new() { ["item"] = "Tea", ["qty"] = 2 };

Console.WriteLine(order.ToJsonString());
Console.WriteLine(order.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine(order.ToString());

Step 2: Run It​

Terminal
dotnet run main.cs
Output
{"item":"Tea","qty":2}
{
"item": "Tea",
"qty": 2
}
{
"item": "Tea",
"qty": 2
}

A zsh terminal where dotnet run main.cs prints the order as JSON on one line, then twice as indented JSON with item Tea and qty 2.

  1. ToJsonString() gave the compact form: one line, no spaces. That's the one to send or store.
  2. With WriteIndented = true, it gave the same JSON with one property per line.
  3. ToString() on an object gave the indented form too.

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

ToString on a Single Value​

The two differ most on a single string value. ToString() gives the text itself, and ToJsonString() gives it as JSON, in quotes:

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

JsonObject order = new() { ["item"] = "Tea" };

Console.WriteLine(order["item"]!.ToString());
Console.WriteLine(order["item"]!.ToJsonString());
Output
Tea
"Tea"

Use ToString() when you want the value to show a person, and ToJsonString() when the result must be valid JSON. The ! tells C# that the property isn't null.

Common Mistakes​

MistakeWhat happensDo this instead
Sending ToString() of an objectIndented JSON over several lines, bigger than it needs to beUse ToJsonString()
Using ToJsonString() to show a string value to a personThe text comes with quotes: "Tea"Use ToString() for display
Writing JsonSerializerOptions without using System.Text.Json;error CS0246: The type or namespace name 'JsonSerializerOptions' could not be found: it lives in System.Text.Json, not in System.Text.Json.NodesAdd both using lines

Troubleshooting​

SymptomLikely causeFix
The JSON spans several linesToString(), or WriteIndented = trueCall ToJsonString() without options
A string value lost its quotesToString() on the valueUse ToJsonString()

FAQ​

Does it need anything special in a one-file program?​

No. Step 1 ran as a one-file program with dotnet run, options included, and printed all three.

Is ToJsonString the same as JsonSerializer.Serialize?​

For a node you already have, ToJsonString() is the direct way to get its JSON. JsonSerializer.Serialize is for turning your own C# objects into JSON.

Conclusion​

node.ToJsonString() returns a JsonObject, JsonArray or value as compact JSON, and ToJsonString(new JsonSerializerOptions { WriteIndented = true }) as indented JSON. ToString() indents objects and gives a string value without its quotes, so keep it for display.

Additional Resources​