using System.Globalization; using System.Text.Json; namespace Cepis; /// /// Reads the faixa block of a 404 body, yielding /// for anything it cannot make sense of. /// /// /// /// A reader rather than a /// because faixa is not a field of any model this library deserializes: /// it hangs off an error body that is otherwise only read for its message. /// /// /// Nothing in here throws. The block is a courtesy on top of a 404 — a missing, /// misshapen or half-empty one must leave the caller with the same clean /// it would have got before the API grew the /// field, never with a parse failure on top of a not-found. /// /// internal static class FaixaReader { /// Turn the faixa element into a range, or null. /// the block, as it came off the wire /// the range, or null when there is nothing usable in it internal static Faixa? Read(JsonElement element) { if (element.ValueKind != JsonValueKind.Object) { return null; } var localidade = ReadString(element, "localidade"); if (string.IsNullOrWhiteSpace(localidade)) { return null; } return new Faixa { Localidade = localidade, UF = ReadString(element, "uf"), Estado = ReadString(element, "estado"), Regiao = ReadString(element, "regiao"), Ibge = ReadString(element, "ibge"), CepIni = ReadString(element, "cep_ini"), CepFim = ReadString(element, "cep_fim"), Ceps = ReadInt(element, "ceps"), }; } /// /// The property as text, or the empty string when it is absent or of a /// shape that is not text. /// /// /// A number is accepted and taken verbatim, the way /// does it for the address fields. /// private static string ReadString(JsonElement owner, string name) { if (!owner.TryGetProperty(name, out var element)) { return ""; } return element.ValueKind switch { JsonValueKind.String => element.GetString() ?? "", JsonValueKind.Number => element.GetRawText(), _ => "", }; } /// The property as a count, or zero when it cannot be read. private static int ReadInt(JsonElement owner, string name) { if (!owner.TryGetProperty(name, out var element)) { return 0; } return element.ValueKind switch { JsonValueKind.Number => element.TryGetInt32(out var number) ? number : 0, JsonValueKind.String => int.TryParse( element.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed) ? parsed : 0, _ => 0, }; } }