microsoft/teams.net
Publicmirrored from https://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Api/Entities/MessageEntity.cs
70lines · modecode
| 1 | using System.Text.Json; |
| 2 | using System.Text.Json.Serialization; |
| 3 | |
| 4 | namespace Microsoft.Teams.Api.Entities; |
| 5 | |
| 6 | [JsonConverter(typeof(IMessageJsonConverter))] |
| 7 | public interface IMessageEntity : IEntity |
| 8 | { |
| 9 | [JsonPropertyName("additionalType")] |
| 10 | [JsonPropertyOrder(10)] |
| 11 | public IList<string>? AdditionalType { get; set; } |
| 12 | |
| 13 | public class IMessageJsonConverter : JsonConverter<IMessageEntity> |
| 14 | { |
| 15 | public override bool CanConvert(Type typeToConvert) |
| 16 | { |
| 17 | return base.CanConvert(typeToConvert); |
| 18 | } |
| 19 | |
| 20 | public override IMessageEntity? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 21 | { |
| 22 | var element = JsonSerializer.Deserialize<JsonElement>(ref reader, options); |
| 23 | |
| 24 | if (!element.TryGetProperty("type", out JsonElement property)) |
| 25 | { |
| 26 | throw new JsonException("entity must have a 'type' property"); |
| 27 | } |
| 28 | |
| 29 | var type = property.Deserialize<string>(options); |
| 30 | |
| 31 | if (type is null) |
| 32 | { |
| 33 | throw new JsonException("failed to deserialize entity 'type' property"); |
| 34 | } |
| 35 | |
| 36 | return type switch |
| 37 | { |
| 38 | "message" => JsonSerializer.Deserialize<MessageEntity>(element.ToString(), options), |
| 39 | "https://schema.org/Message" => JsonSerializer.Deserialize<OMessageEntity>(element.ToString(), options), |
| 40 | _ => throw new JsonException($"entity type '{type}' is not supported") |
| 41 | }; |
| 42 | } |
| 43 | |
| 44 | public override void Write(Utf8JsonWriter writer, IMessageEntity value, JsonSerializerOptions options) |
| 45 | { |
| 46 | if (value is MessageEntity message) |
| 47 | { |
| 48 | JsonSerializer.Serialize(writer, message, options); |
| 49 | return; |
| 50 | } |
| 51 | |
| 52 | if (value is OMessageEntity oMessage) |
| 53 | { |
| 54 | JsonSerializer.Serialize(writer, oMessage, options); |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | JsonSerializer.Serialize(writer, value, options); |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | public class MessageEntity : Entity, IMessageEntity |
| 64 | { |
| 65 | [JsonPropertyName("additionalType")] |
| 66 | [JsonPropertyOrder(10)] |
| 67 | public IList<string>? AdditionalType { get; set; } |
| 68 | |
| 69 | public MessageEntity() : base("message") { } |
| 70 | } |