Created
April 24, 2021 11:50
-
-
Save mr5z/329f1826288be485767f097680c7c620 to your computer and use it in GitHub Desktop.
JSON Path to Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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