|
| 1 | +using System.Text.Json; |
| 2 | +using System.Text.Json.Nodes; |
| 3 | + |
| 4 | +using k8s; |
| 5 | + |
| 6 | +namespace KubeOps.Operator.Serialization; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// This is a wrapper around <see cref="KubernetesJson"/> to allow for |
| 10 | +/// more flexible configuration and serialization/deserialization of Kubernetes objects. |
| 11 | +/// </summary> |
| 12 | +public static class KubernetesJsonSerializer |
| 13 | +{ |
| 14 | + private static readonly Lazy<JsonSerializerOptions> Options = new(() => |
| 15 | + { |
| 16 | + JsonSerializerOptions options = null!; |
| 17 | + KubernetesJson.AddJsonOptions(c => options = c); |
| 18 | + return options; |
| 19 | + }); |
| 20 | + |
| 21 | + public static JsonSerializerOptions SerializerOptions => Options.Value; |
| 22 | + |
| 23 | + public static TValue Deserialize<TValue>(string json, JsonSerializerOptions? options = null) => |
| 24 | + KubernetesJson.Deserialize<TValue>(json, options ?? Options.Value); |
| 25 | + |
| 26 | + public static TValue Deserialize<TValue>(Stream json, JsonSerializerOptions? options = null) => |
| 27 | + KubernetesJson.Deserialize<TValue>(json, options ?? Options.Value); |
| 28 | + |
| 29 | + public static TValue Deserialize<TValue>(JsonDocument json, JsonSerializerOptions? options = null) => |
| 30 | + json.Deserialize<TValue>(options ?? Options.Value) ?? |
| 31 | + throw new JsonException("Deserialization returned null."); |
| 32 | + |
| 33 | + public static TValue Deserialize<TValue>(JsonElement json, JsonSerializerOptions? options = null) => |
| 34 | + json.Deserialize<TValue>(options ?? Options.Value) ?? |
| 35 | + throw new JsonException("Deserialization returned null."); |
| 36 | + |
| 37 | + public static TValue Deserialize<TValue>(JsonNode json, JsonSerializerOptions? options = null) => |
| 38 | + json.Deserialize<TValue>(options ?? Options.Value) ?? |
| 39 | + throw new JsonException("Deserialization returned null."); |
| 40 | + |
| 41 | + public static string Serialize(object value, JsonSerializerOptions? options = null) => |
| 42 | + KubernetesJson.Serialize(value, options ?? Options.Value); |
| 43 | +} |
0 commit comments