// #nullable enable using System; using System.Text.Json; using CarpaNet.Models; namespace CarpaNet.Parsing; /// /// Parses Lexicon JSON files into strongly-typed models. /// public static class LexiconParser { private static readonly JsonSerializerOptions SerializerOptions = new() { PropertyNameCaseInsensitive = false, ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; /// /// Parses a Lexicon JSON string into a LexiconDocument. /// /// The JSON content to parse. /// The parsed LexiconDocument, or null if parsing fails. public static LexiconDocument? Parse(string? json) { if (string.IsNullOrWhiteSpace(json)) { return null; } try { return JsonSerializer.Deserialize(json!, SerializerOptions); } catch (JsonException) { return null; } } /// /// Tries to parse a Lexicon JSON string. /// /// The JSON content to parse. /// The parsed document if successful. /// The error message if parsing fails. /// True if parsing succeeded, false otherwise. public static bool TryParse(string? json, out LexiconDocument? document, out string? error) { document = null; error = null; if (string.IsNullOrWhiteSpace(json)) { error = "Empty or null JSON content"; return false; } try { document = JsonSerializer.Deserialize(json!, SerializerOptions); if (document == null) { error = "Deserialization returned null"; return false; } return true; } catch (JsonException ex) { error = ex.Message; return false; } } }