Created
September 30, 2021 22:28
-
-
Save rido-min/d11aa66633c4eacb0c1d0527d5e2017e to your computer and use it in GitHub Desktop.
JSONExtensions
This file contains hidden or 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
| // https://stackoverflow.com/questions/58138793/system-text-json-jsonelement-toobject-workaround | |
| // https://stackoverflow.com/questions/61553962/getting-nested-properties-with-system-text-json | |
| static class JsonExtensions | |
| { | |
| public static JsonElement GetJsonElement(this JsonElement jsonElement, string path) | |
| { | |
| if (jsonElement.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) | |
| return default; | |
| string[] segments = path.Split('.', StringSplitOptions.RemoveEmptyEntries); | |
| foreach (var segment in segments) | |
| { | |
| jsonElement = jsonElement.TryGetProperty(segment, out var value) ? value : default; | |
| if (jsonElement.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) | |
| return default; | |
| } | |
| return jsonElement; | |
| } | |
| public static string GetJsonElementValue(this JsonElement jsonElement) => | |
| jsonElement.ValueKind != JsonValueKind.Null && | |
| jsonElement.ValueKind != JsonValueKind.Undefined | |
| ? jsonElement.ToString() | |
| : default; | |
| public static T ToObject<T>(this JsonElement element) | |
| { | |
| var json = element.GetRawText(); | |
| return JsonSerializer.Deserialize<T>(json); | |
| } | |
| public static T ToObject<T>(this JsonDocument document) | |
| { | |
| var json = document.RootElement.GetRawText(); | |
| return JsonSerializer.Deserialize<T>(json); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment