Serialization
Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be stored and transferred.
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.
Comments