diff --git a/src/client/spark_core/Json/JsonExtensions.cs b/src/client/spark_core/Json/JsonExtensions.cs new file mode 100644 index 000000000..8cf83329f --- /dev/null +++ b/src/client/spark_core/Json/JsonExtensions.cs @@ -0,0 +1,44 @@ +#nullable enable +namespace Spark.Core.Json; + +using Spark.Core.Disposables; + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; + +public static class JsonExtensions { + public static bool ReadObject(this Utf8JsonReader reader) { + return reader.Read() && reader.TokenType == JsonTokenType.StartObject; + } + + public static bool ReadPropertyName( + this Utf8JsonReader reader, [NotNullWhen(true)]out string? propertyName) { + if (reader.Read() && reader.TokenType == JsonTokenType.PropertyName) { + propertyName = reader.GetString()!; + return true; + } + propertyName = null; + return false; + } + + public static IDisposable WriteArray(this Utf8JsonWriter writer) { + writer.WriteStartArray(); + return Disposable.Create(writer.WriteEndArray); + } + + public static IDisposable WriteArray(this Utf8JsonWriter writer, string propertyName) { + writer.WriteStartArray(propertyName); + return Disposable.Create(writer.WriteEndArray); + } + + public static IDisposable WriteObject(this Utf8JsonWriter writer) { + writer.WriteStartObject(); + return Disposable.Create(writer.WriteEndObject); + } + + public static IDisposable WriteObject(this Utf8JsonWriter writer, string propertyName) { + writer.WritePropertyName(propertyName); + return Disposable.Create(writer.WriteEndObject); + } +}