using System; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; namespace Mqtt.Models { public class HTTPBody { [JsonConverter(typeof(DictionaryStringObjectJsonConverter))] public Dictionary data { get; set; } } public class DictionaryStringObjectJsonConverter : JsonConverter> { public override Dictionary Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException($"JsonTokenType was of type {reader.TokenType}, only objects are supported"); } Dictionary dictionary = new Dictionary(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return dictionary; } if (reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException("JsonTokenType was not PropertyName"); } string @string = reader.GetString(); if (string.IsNullOrWhiteSpace(@string)) { throw new JsonException("Failed to get property name"); } reader.Read(); dictionary.Add(@string, ExtractValue(ref reader, options)); } return dictionary; } public override void Write(Utf8JsonWriter writer, Dictionary value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value, options); } private object ExtractValue(ref Utf8JsonReader reader, JsonSerializerOptions options) { switch (reader.TokenType) { case JsonTokenType.String: { if (reader.TryGetDateTime(out var value2)) { return value2; } return reader.GetString(); } case JsonTokenType.False: return false; case JsonTokenType.True: return true; case JsonTokenType.Null: return null; case JsonTokenType.Number: { if (reader.TryGetInt64(out var value)) { return value; } return reader.GetDecimal(); } case JsonTokenType.StartObject: return Read(ref reader, null, options); case JsonTokenType.StartArray: { List list = new List(); while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) { list.Add(ExtractValue(ref reader, options)); } return list; } default: throw new JsonException($"'{reader.TokenType}' is not supported"); } } } }