Skip to content

Instantly share code, notes, and snippets.

@mr5z
Created April 24, 2021 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr5z/329f1826288be485767f097680c7c620 to your computer and use it in GitHub Desktop.
Save mr5z/329f1826288be485767f097680c7c620 to your computer and use it in GitHub Desktop.
JSON Path to Object
public async Task<T?> GetValue<T>(string path, JsonSerializerOptions? options, CancellationToken cancellationToken)
{
using var stream = GetStream();
using var jsonDocument = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
var root = jsonDocument.RootElement;
var jsonPath = JsonPath.Parse(path);
var pathResult = jsonPath.Evaluate(root);
if (pathResult.Error != null)
throw new InvalidOperationException(pathResult.Error);
var matches = pathResult.Matches!;
var first = matches.First();
var value = typeof(T) == typeof(string) ?
$"\"{first.Value}\"" :
$"{first.Value}";
return JsonSerializer.Deserialize<T?>(value, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment