Successfully added
.NET
by Patrik
Avoid Exceptions When Accessing Properties on a JsonElement
When working with JsonElement
in C#, calling methods like TryGetProperty
on a default or uninitialized JsonElement
can cause runtime exceptions. This usually happens when the JsonElement
has not been properly assigned a value.
To avoid this issue, always check whether the JsonElement
is valid before accessing its properties. A safe way to do this is by checking its ValueKind
.
Here’s a safer extension method that returns a string property only if it exists and the element is valid:
public static string? GetStringProperty(this JsonElement element, string propertyName)
{
if (element.ValueKind == JsonValueKind.Undefined)
return null;
return element.TryGetProperty(propertyName, out var prop) && prop.ValueKind == JsonValueKind.String
? prop.GetString()
: null;
}
This ensures that your code won’t throw an InvalidOperationException
when the JsonElement
is default
.
Use this method when reading from JSON documents where property existence isn’t guaranteed.
json
csharp
dotnet
safety
extensionmethods
Referenced in:
Comments