using System; using System.Text.Json; using System.Text.Json.Serialization; namespace Jugenddienst_Stunden.Models; internal sealed class JsonFlexibleInt32Converter : JsonConverter { public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { switch (reader.TokenType) { case JsonTokenType.Number: if (reader.TryGetInt32(out var n)) return n; // Fallback via double to cover edge cases var d = reader.GetDouble(); return (int)d; case JsonTokenType.String: var s = reader.GetString(); if (string.IsNullOrWhiteSpace(s)) return 0; s = s.Trim(); // Some APIs embed id like "141|..." -> take leading numeric part int i = 0; int sign = 1; int idx = 0; if (s.StartsWith("-")) { sign = -1; idx = 1; } for (; idx < s.Length; idx++) { char c = s[idx]; if (c < '0' || c > '9') break; i = i * 10 + (c - '0'); } if (idx > 0 && (idx > 1 || sign == 1)) return i * sign; if (int.TryParse(s, out var parsed)) return parsed; if (long.TryParse(s, out var l)) return (int)l; throw new JsonException($"Cannot convert string '{s}' to Int32."); case JsonTokenType.Null: return 0; default: throw new JsonException($"Token {reader.TokenType} is not valid for Int32."); } } public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) => writer.WriteNumberValue(value); } internal sealed class JsonFlexibleNullableInt32Converter : JsonConverter { public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; // Reuse non-nullable converter var conv = new JsonFlexibleInt32Converter(); return conv.Read(ref reader, typeof(int), options); } public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options) { if (value.HasValue) writer.WriteNumberValue(value.Value); else writer.WriteNullValue(); } }