Extension methods for System.Text.Json.JsonElement to identify a specific value through a JSON Pointer (RFC 6901).
$ dotnet add package JsonPtrThis project provides extension methods for the System.Text.Json.JsonElement type to support JSON Pointer (RFC 6901) resolution.
GetElement: Retrieves a JSON element or throws a JsonPointerException on failure.GetElementOrNull: Retrieves a JSON element or returns null on failure.TryGetElement: Attempts to retrieve a JSON element, returning a success flag and error details if applicable.GetElementRetrieves a JSON element at the specified pointer, throwing an exception if resolution fails.
var json = @"{""person"":{""name"":""John""}}";
var element = JsonDocument.Parse(json).RootElement;
try
{
var nameElement = element.GetElement("/person/name");
Console.WriteLine(nameElement.GetString()); // Output: John
var invalidElement = element.GetElement("/person/age");
}
catch (JsonPointerException ex)
{
Console.WriteLine(ex.Message); // Handles invalid pointers
}
GetElementOrNullRetrieves a JSON element or returns null if the pointer cannot be resolved.
using System.Text.Json;
var json = @"{""person"":{""name"":""John""}}";
var element = JsonDocument.Parse(json).RootElement;
var name = element.GetElementOrNull("/person/name");
Console.WriteLine(name.Value.GetString()); // Output: John
var age = element.GetElementOrNull("/person/age");
Console.WriteLine(age.HasValue ? age.Value.GetString() : "Not found"); // Output: Not found
TryGetElementAttempts to retrieve a JSON element, returning success status and error details.
using System.Text.Json;
var json = @"{""person"":{""name"":""John""}}";
var element = JsonDocument.Parse(json).RootElement;
if (element.TryGetElement("/person/name", out JsonElement? result, out JsonPointerError? error))
{
Console.WriteLine(result.Value.GetString()); // Output: John
}
else
{
Console.WriteLine(error.Message); // Handles failure
}
/property accesses an object property./0 accesses an array element by index.~0 for ~ and ~1 for / in escaped keys (e.g., /foo~1bar for key foo/bar)."") refers to the root element.