Skip to main content

How to Read a JSON Property with JsonElement.GetProperty in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

weather.GetProperty("city") finds the property called city in a JSON object and gives you its value as a JsonElement. When the property isn't there, it throws, so a JSON without it can't slip through unnoticed.

Microsoft's reference: Gets a JsonElement representing the value of a required property identified by propertyName. Note the word required: the property has to be there. For a missing one, the reference lists a KeyNotFoundException: No property was found with the requested name.

Syntax​

Syntax
JsonElement <value> = <element>.GetProperty("<name>");
PartWhat it is
<element>A JsonElement that holds a JSON object, such as document.RootElement
"<name>"The property's name, written exactly as in the JSON
<value>The property's value, as a JsonElement. Read it with a method such as GetString() or GetInt32(), or call GetProperty on it again when it holds an object

The reference on the name: Property name matching is performed as an ordinal, case-sensitive comparison. So City and city are different names.

The Example​

A console app called JsonGetProperty reads a small weather report: a city, a temperature, and a wind object with a speed and a direction. Then it asks for humidity, which the JSON doesn't have.

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 JsonGetProperty
cd JsonGetProperty
Output
The template "Console App" was created successfully.

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

dotnet new console -n JsonGetProperty creates a folder named JsonGetProperty 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 JsonGetProperty.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 = """
{
"city": "Lisbon",
"temperature": 21,
"wind": { "speed": 14, "direction": "NW" }
}
""";

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

JsonDocument.Parse reads the text, and RootElement is the object between the outer braces, as a JsonElement. The using disposes the document when the program ends.

Then read two properties:

Program.cs (reading two properties)
// GetProperty returns the value of one property, as a JsonElement.
string? city = weather.GetProperty("city").GetString();
int temperature = weather.GetProperty("temperature").GetInt32();
Console.WriteLine($"{city}: {temperature} degrees");
  • GetProperty("city") returns the value of city as a JsonElement, and GetString() reads it as a C# string.
  • GetProperty("temperature") returns the number, and GetInt32() reads it as an int.

Next, go one level down:

Program.cs (one level down)
// The value of "wind" is an object, so call GetProperty on it to go one level down.
JsonElement wind = weather.GetProperty("wind");
Console.WriteLine($"wind is a JSON {wind.ValueKind}");
Console.WriteLine($"wind: {wind.GetProperty("speed").GetInt32()} km/h from the {wind.GetProperty("direction").GetString()}");

The value of wind is an object, so GetProperty("wind") returns an element whose ValueKind is Object. GetProperty works on it the same way as on the root: wind.GetProperty("speed") and wind.GetProperty("direction").

Last, ask for a property that isn't there:

Program.cs (a missing property)
// A property that isn't in the JSON makes GetProperty throw.
try
{
weather.GetProperty("humidity");
}
catch (KeyNotFoundException exception)
{
Console.WriteLine($"humidity: {exception.GetType().Name}: {exception.Message}");
}

The JSON has no humidity, so GetProperty throws a KeyNotFoundException, and the catch prints its type and message.

Step 3: Run It​

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

Terminal
dotnet run
Output
Lisbon: 21 degrees
wind is a JSON Object
wind: 14 km/h from the NW
humidity: KeyNotFoundException: The given key was not present in the dictionary.

macOS-style terminal window titled Terminal — JsonGetProperty showing dotnet run printing Lisbon: 21 degrees, wind is a JSON Object, wind: 14 km/h from the NW, and humidity: KeyNotFoundException: The given key was not present in the dictionary.

GetProperty found city (Lisbon) and temperature (21), and one level down, the wind's speed (14) and direction (NW). For humidity, it threw a KeyNotFoundException with the message The given key was not present in the dictionary. That's the point of GetProperty: a property the code can't do without fails loudly, on the line that reads it.

The Complete File​

macOS-style code window titled Program.cs — JsonGetProperty showing a weather JSON with a city, a temperature and a wind object, JsonDocument.Parse, GetProperty calls that read the city, the temperature and the wind's speed and direction, and a try block where GetProperty for humidity throws a KeyNotFoundException that the catch prints

Program.cs
using System.Text.Json;

string json = """
{
"city": "Lisbon",
"temperature": 21,
"wind": { "speed": 14, "direction": "NW" }
}
""";

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

// GetProperty returns the value of one property, as a JsonElement.
string? city = weather.GetProperty("city").GetString();
int temperature = weather.GetProperty("temperature").GetInt32();
Console.WriteLine($"{city}: {temperature} degrees");

// The value of "wind" is an object, so call GetProperty on it to go one level down.
JsonElement wind = weather.GetProperty("wind");
Console.WriteLine($"wind is a JSON {wind.ValueKind}");
Console.WriteLine($"wind: {wind.GetProperty("speed").GetInt32()} km/h from the {wind.GetProperty("direction").GetString()}");

// A property that isn't in the JSON makes GetProperty throw.
try
{
weather.GetProperty("humidity");
}
catch (KeyNotFoundException exception)
{
Console.WriteLine($"humidity: {exception.GetType().Name}: {exception.Message}");
}

Common Mistakes​

MistakeWhat happensDo this instead
Getting the name's case wrongGetProperty("City") threw KeyNotFoundException: The given key was not present in the dictionary. for a property written cityWrite the name exactly as the JSON does: GetProperty("city") returned Lisbon
GetProperty for a property that may be missingIt throws a KeyNotFoundException, as humidity did in the exampleUse TryGetProperty, which returned False for humidity instead of throwing
Calling GetProperty on an arrayOn an array of days, it threw InvalidOperationException: The requested operation requires an element of type 'Object', but the target element has type 'Array'.Pick an item first: days[0].GetProperty("city") returned Lisbon
Using an element after its JsonDocument is disposedA method returned document.RootElement from inside a using, and GetProperty on it threw ObjectDisposedException: Cannot access a disposed object. Object name: 'JsonDocument'.Read the values while the document is alive, or return document.RootElement.Clone(). The reference: Gets a JsonElement that can be safely stored beyond the lifetime of the original JsonDocument. The clone still read Lisbon

FAQ​

What does GetProperty do with a property whose value is null?​

It returns it, without throwing: the property is there, its value is a JSON null. For {"city":null}, GetProperty("city") returned an element whose ValueKind is Null, and GetString() on it returned null. Only a property that's missing altogether throws.

What if the JSON has the same property twice?​

GetProperty takes the last one. For {"city":"Lisbon","city":"Porto"}, GetProperty("city") returned Porto. The reference: If a property is defined multiple times for the same object, the method matches the last such definition.

Conclusion​

element.GetProperty("name") gives you a property's value as a JsonElement, ready for GetString(), GetInt32() or another GetProperty. Match the name's case exactly, call it on objects only, and use TryGetProperty for properties that may be missing.

Additional Resources​