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