|
| 1 | +using System.Text.Json; |
| 2 | +using System.Text.Json.Nodes; |
| 3 | + |
| 4 | +namespace glTF |
| 5 | +{ |
| 6 | + internal static class JsonExtensions |
| 7 | + { |
| 8 | + public static JsonArray? GetArray(this JsonNode node, string propertyName, JsonArray? defaultValue = null) |
| 9 | + { |
| 10 | + var propertyNode = node[propertyName]; |
| 11 | + if (propertyNode == null || propertyNode.GetValueKind() != JsonValueKind.Array) |
| 12 | + { |
| 13 | + return defaultValue; |
| 14 | + } |
| 15 | + |
| 16 | + return propertyNode.AsArray(); |
| 17 | + } |
| 18 | + |
| 19 | + public static int GetInt(this JsonNode node, string propertyName, int defaultValue = -1) |
| 20 | + { |
| 21 | + var propertyNode = node[propertyName]; |
| 22 | + if (propertyNode == null || propertyNode.GetValueKind() != JsonValueKind.Number) |
| 23 | + { |
| 24 | + return defaultValue; |
| 25 | + } |
| 26 | + |
| 27 | + return propertyNode.GetValue<int>(); |
| 28 | + } |
| 29 | + |
| 30 | + public static string? GetString(this JsonNode node, string propertyName, string? defaultValue = null) |
| 31 | + { |
| 32 | + var propertyNode = node[propertyName]; |
| 33 | + if (propertyNode == null || propertyNode.GetValueKind() != JsonValueKind.String) |
| 34 | + { |
| 35 | + return defaultValue; |
| 36 | + } |
| 37 | + |
| 38 | + return propertyNode.GetValue<string>(); |
| 39 | + } |
| 40 | + |
| 41 | + public static string? GetLocalPath(this JsonNode node, string propertyName, Uri baseUri, string? defaultValue = null) |
| 42 | + { |
| 43 | + var uriString = node.GetString(propertyName); |
| 44 | + if (uriString == null) |
| 45 | + { |
| 46 | + return defaultValue; |
| 47 | + } |
| 48 | + |
| 49 | + if (!Uri.TryCreate(baseUri, uriString, out var uri) || !uri.IsFile) |
| 50 | + { |
| 51 | + return defaultValue; |
| 52 | + } |
| 53 | + |
| 54 | + return uri.LocalPath; |
| 55 | + } |
| 56 | + |
| 57 | + public static void SetInt(this JsonNode jsonNode, string propertyName, int value, int defaultValue) |
| 58 | + { |
| 59 | + if (value == defaultValue) |
| 60 | + { |
| 61 | + jsonNode.AsObject().Remove(propertyName); |
| 62 | + } |
| 63 | + else |
| 64 | + { |
| 65 | + jsonNode[propertyName] = JsonValue.Create(value); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public static bool Remove(this JsonNode node, string propertyName) |
| 70 | + { |
| 71 | + if (node.GetValueKind() != JsonValueKind.Object) |
| 72 | + { |
| 73 | + return false; |
| 74 | + } |
| 75 | + |
| 76 | + return node.AsObject().Remove(propertyName); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments