microsoft/teams.net
Publicmirrored from https://github.com/microsoft/teams.netAvailable
core/src/Microsoft.Teams.Apps/State/StateSerializer.cs
44lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using System.Text.Json; |
| 5 | using System.Text.Json.Serialization; |
| 6 | using System.Text.Json.Serialization.Metadata; |
| 7 | using Microsoft.Teams.Apps.Schema; |
| 8 | |
| 9 | namespace Microsoft.Teams.Apps.State; |
| 10 | |
| 11 | /// <summary> |
| 12 | /// Serialization helpers for state scope documents. A state scope is an open-typed bag |
| 13 | /// (<c>Dictionary<string, object?></c>), so serialization is fundamentally reflection-based. |
| 14 | /// The canonical <see cref="TeamsActivityJsonContext"/> supplies fast, source-generated metadata for |
| 15 | /// the primitives and <see cref="JsonElement"/> values that commonly appear; the combined reflection |
| 16 | /// resolver handles arbitrary user POCO values. |
| 17 | /// </summary> |
| 18 | internal static class StateSerializer |
| 19 | { |
| 20 | /// <summary> |
| 21 | /// Serializer options reusing the canonical Teams source-generated context for known primitive and |
| 22 | /// framework types, combined with a reflection resolver so arbitrary user POCO values still |
| 23 | /// serialize. State stores user-defined types, so it cannot be a closed-world, fully source-generated |
| 24 | /// serializer like the activity pipeline — hence the reflection fallback. |
| 25 | /// </summary> |
| 26 | internal static readonly JsonSerializerOptions Options = new() |
| 27 | { |
| 28 | TypeInfoResolver = JsonTypeInfoResolver.Combine(TeamsActivityJsonContext.Default, new DefaultJsonTypeInfoResolver()), |
| 29 | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| 30 | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| 31 | }; |
| 32 | |
| 33 | /// <summary>Serializes a scope's values to canonical UTF-8 JSON (used for change detection and storage).</summary> |
| 34 | internal static byte[] Serialize(IDictionary<string, object?> values) |
| 35 | => JsonSerializer.SerializeToUtf8Bytes(values, Options); |
| 36 | |
| 37 | /// <summary>Deserializes a scope's values from UTF-8 JSON. Values are returned as <see cref="JsonElement"/>.</summary> |
| 38 | internal static Dictionary<string, object?> Deserialize(ReadOnlySpan<byte> utf8Json) |
| 39 | => JsonSerializer.Deserialize<Dictionary<string, object?>>(utf8Json, Options) ?? []; |
| 40 | |
| 41 | /// <summary>Converts a stored <see cref="JsonElement"/> to the requested type.</summary> |
| 42 | internal static T? Convert<T>(JsonElement element) |
| 43 | => element.Deserialize<T>(Options); |
| 44 | } |
| 45 | |