|
1 | 1 | using System; |
| 2 | +using System.Collections.Generic; |
2 | 3 | using System.Linq; |
3 | 4 | using System.Text.Json; |
4 | 5 |
|
5 | 6 | namespace GitReleaseManager.Core.Extensions |
6 | 7 | { |
7 | 8 | internal static class JsonExtensions |
8 | 9 | { |
| 10 | + /// <summary> |
| 11 | + /// Get a JsonElement from a path. Each level in the path is seperated by a dot. |
| 12 | + /// </summary> |
| 13 | + /// <param name="jsonElement">The parent Json element.</param> |
| 14 | + /// <param name="path">The path of the desired child element.</param> |
| 15 | + /// <returns>The child element.</returns> |
9 | 16 | public static JsonElement GetJsonElement(this JsonElement jsonElement, string path) |
10 | 17 | { |
11 | 18 | if (jsonElement.ValueKind is JsonValueKind.Null || jsonElement.ValueKind is JsonValueKind.Undefined) |
@@ -39,6 +46,36 @@ public static JsonElement GetJsonElement(this JsonElement jsonElement, string pa |
39 | 46 | return jsonElement; |
40 | 47 | } |
41 | 48 |
|
| 49 | + /// <summary> |
| 50 | + /// Get the first JsonElement matching a path from the provided list of paths. |
| 51 | + /// </summary> |
| 52 | + /// <param name="jsonElement">The parent Json element.</param> |
| 53 | + /// <param name="paths">The path of the desired child element.</param> |
| 54 | + /// <returns>The child element.</returns> |
| 55 | + public static JsonElement GetFirstJsonElement(this JsonElement jsonElement, IEnumerable<string> paths) |
| 56 | + { |
| 57 | + if (jsonElement.ValueKind is JsonValueKind.Null || jsonElement.ValueKind is JsonValueKind.Undefined) |
| 58 | + { |
| 59 | + return default(JsonElement); |
| 60 | + } |
| 61 | + |
| 62 | + var element = default(JsonElement); |
| 63 | + |
| 64 | + foreach (var path in paths) |
| 65 | + { |
| 66 | + element = jsonElement.GetJsonElement(path); |
| 67 | + |
| 68 | + if (element.ValueKind is JsonValueKind.Null || element.ValueKind is JsonValueKind.Undefined) |
| 69 | + { |
| 70 | + continue; |
| 71 | + } |
| 72 | + |
| 73 | + break; |
| 74 | + } |
| 75 | + |
| 76 | + return element; |
| 77 | + } |
| 78 | + |
42 | 79 | public static string GetJsonElementValue(this JsonElement jsonElement) => jsonElement.ValueKind != JsonValueKind.Null && |
43 | 80 | jsonElement.ValueKind != JsonValueKind.Undefined |
44 | 81 | ? jsonElement.ToString() |
|
0 commit comments