using System; using System.Globalization; using System.Text.Json.Serialization; using System.Text.Json; using AsbCloudApp.Data.GTR; namespace AsbCloudWebApi.Converters { public class JsonValueJsonConverter : JsonConverter { public override JsonValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var stringVal = reader.GetString() ?? string.Empty; return new JsonValue(stringVal); } if (reader.TokenType == JsonTokenType.Number) { if (reader.TryGetInt32(out int intVal)) return new JsonValue(intVal); if (reader.TryGetDouble(out double doubleVal)) return new JsonValue((float)doubleVal); } throw new FormatException($"Wrong format at position {reader.Position}"); } public override void Write(Utf8JsonWriter writer, JsonValue value, JsonSerializerOptions options) { if (value.Value is string strValue) { writer.WriteStringValue(FormatString(strValue)); return; } if (value.Value is int intValue) { writer.WriteNumberValue(intValue); return; } if (value.Value is short shortValue) { writer.WriteNumberValue(shortValue); return; } if (value.Value is float floatValue) { writer.WriteRawValue(floatValue.ToString("#0.0##", CultureInfo.InvariantCulture), true); return; } if (value.Value is double doubleValue) { writer.WriteRawValue(doubleValue.ToString("#0.0##", CultureInfo.InvariantCulture), true); return; } var typeName = value.Value.GetType().Name; throw new NotImplementedException($"{typeName} is not supported type for WITS value"); } private static string FormatString(string value) => value .Replace("\"", "") .Trim() .Replace("\r", "") .Replace("\n", ""); } }