Skip to main content

How to Get the Raw JSON Text of a JsonElement with GetRawText in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

element.GetRawText() gives you a JSON value exactly as the JSON text writes it: a string with its quotes, a number with every digit, an object with its spaces. Use it when you need the JSON itself, not a C# value.

Microsoft's reference: Gets a string that represents the original input data backing this value. Nothing is converted: you get back the characters of the JSON text that the value was read from.

Syntax​

Syntax
string <text> = <element>.GetRawText();
PartWhat it is
<element>Any JsonElement: a string, a number, an object, an array, true, false or null
GetRawText()Returns that value's JSON text. The reference: The original input data backing this value.
<text>A C# string that holds the JSON text

The Example​

A console app called JsonRawText reads a desk lamp's details: a name, a price, a size object and an array of colors. It prints the raw text of each value, then reads two of them with GetString() and GetDouble() to compare.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n JsonRawText
cd JsonRawText
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/JsonRawText/JsonRawText.csproj:
Determining projects to restore...
Restored /Users/you/source/JsonRawText/JsonRawText.csproj (in 39 ms).
Restore succeeded.

dotnet new console -n JsonRawText creates a folder named JsonRawText with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or JsonRawText.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First parse the JSON:

Program.cs (parsing)
using System.Text.Json;

string json = """
{
"name": "Desk lamp",
"price": 24.90,
"size": { "width": 15, "height": 40 },
"colors": ["black", "white"]
}
""";

using JsonDocument document = JsonDocument.Parse(json);
JsonElement lamp = document.RootElement;

JsonDocument.Parse reads the text, and RootElement is the lamp object, as a JsonElement.

Then print the raw text of each value:

Program.cs (the raw text)
// GetRawText returns each value exactly as it's written in the JSON text.
Console.WriteLine($"name: {lamp.GetProperty("name").GetRawText()}");
Console.WriteLine($"price: {lamp.GetProperty("price").GetRawText()}");
Console.WriteLine($"size: {lamp.GetProperty("size").GetRawText()}");
Console.WriteLine($"colors: {lamp.GetProperty("colors").GetRawText()}");

GetProperty finds each property, and GetRawText() returns its value's JSON text. It works the same way for every kind of value: here a string, a number, an object and an array.

Last, read two of the values with the typed methods:

Program.cs (the typed values)
// The typed methods convert the value instead.
Console.WriteLine($"GetString(): {lamp.GetProperty("name").GetString()}");
Console.WriteLine($"GetDouble(): {lamp.GetProperty("price").GetDouble()}");

GetString() reads the name as a C# string, and GetDouble() reads the price as a double.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
name: "Desk lamp"
price: 24.90
size: { "width": 15, "height": 40 }
colors: ["black", "white"]
GetString(): Desk lamp
GetDouble(): 24.9

macOS-style terminal window titled Terminal — JsonRawText showing dotnet run printing the name Desk lamp still in its quotes, the price as 24.90, the size object and the colors array as written in the JSON, then GetString(): Desk lamp and GetDouble(): 24.9

Each raw text matches the JSON character for character:

  • The name kept its quotes, "Desk lamp", where GetString() gave Desk lamp.
  • The price kept its trailing zero, 24.90, where GetDouble() gave 24.9.
  • The object and the array came back with the same spaces as in the JSON.

The Complete File​

macOS-style code window titled Program.cs — JsonRawText showing a desk lamp JSON with a name, a price of 24.90, a size object and a colors array, JsonDocument.Parse, four lines that print GetRawText for each property, and two lines that print GetString for the name and GetDouble for the price

Program.cs
using System.Text.Json;

string json = """
{
"name": "Desk lamp",
"price": 24.90,
"size": { "width": 15, "height": 40 },
"colors": ["black", "white"]
}
""";

using JsonDocument document = JsonDocument.Parse(json);
JsonElement lamp = document.RootElement;

// GetRawText returns each value exactly as it's written in the JSON text.
Console.WriteLine($"name: {lamp.GetProperty("name").GetRawText()}");
Console.WriteLine($"price: {lamp.GetProperty("price").GetRawText()}");
Console.WriteLine($"size: {lamp.GetProperty("size").GetRawText()}");
Console.WriteLine($"colors: {lamp.GetProperty("colors").GetRawText()}");

// The typed methods convert the value instead.
Console.WriteLine($"GetString(): {lamp.GetProperty("name").GetString()}");
Console.WriteLine($"GetDouble(): {lamp.GetProperty("price").GetDouble()}");

Common Mistakes​

MistakeWhat happensDo this instead
Using GetRawText() to read a string's valueThe quotes come along, as "Desk lamp" showed, and so do escape sequences: a string with escaped quotes came back with its backslashesUse GetString(), which returns the text without quotes or escapes
Expecting compact JSONGetRawText() keeps the input's spaces: { "width": 15, "height": 40 }For compact JSON, JsonSerializer.Serialize(size) returned {"width":15,"height":40}
Calling it after the JsonDocument is disposedAn element returned from a method whose using had ended threw ObjectDisposedException: Cannot access a disposed object. Object name: 'JsonDocument'.Call GetRawText() while the document is alive: inside the using, it returned { "width": 15, "height": 40 }

FAQ​

Is GetRawText the same as ToString?​

Not for strings, true, false and null. For the name, ToString() gave Desk lamp and GetRawText() gave "Desk lamp". For true, they gave True and true, and for null, an empty string and null. For the price and the size object, both gave the same text. The reference for ToString(): For JsonValueKind.String, the value of GetString() is returned. And for numbers, objects and arrays: For other types, the value of GetRawText() is returned.

Conclusion​

GetRawText() returns a JSON value's text exactly as the input wrote it, for any kind of value. Use it when you need the JSON itself, and use GetString(), GetDouble() and the other typed methods when you need the value.

Additional Resources​