diff --git a/lib/bademagic_module/models/data.dart b/lib/bademagic_module/models/data.dart index fa77b012d..179573220 100644 --- a/lib/bademagic_module/models/data.dart +++ b/lib/bademagic_module/models/data.dart @@ -11,9 +11,27 @@ class Data { // Convert JSON to Data object factory Data.fromJson(Map json) { + if (!json.containsKey('messages')) { + throw Exception('Invalid JSON: Missing "messages" key'); + } + + if (json['messages'] is! List) { + throw Exception('Invalid JSON: "messages" must be a list'); + } + + if (json['messages'].isEmpty) { + throw Exception('Invalid JSON: "messages" list is empty'); + } + var messagesFromJson = json['messages'] as List; + + if (messagesFromJson.any((message) => message == null)) { + throw Exception('Invalid JSON: "messages" list contains null values'); + } + List messageList = messagesFromJson.map((message) => Message.fromJson(message)).toList(); + return Data(messages: messageList); } } diff --git a/lib/bademagic_module/models/messages.dart b/lib/bademagic_module/models/messages.dart index 4c025d14b..0ade4703a 100644 --- a/lib/bademagic_module/models/messages.dart +++ b/lib/bademagic_module/models/messages.dart @@ -27,10 +27,31 @@ class Message { // Convert JSON to Message object factory Message.fromJson(Map json) { + if (!json.containsKey('text')) { + throw Exception('Invalid JSON: Message missing "text" key'); + } + + if (!json.containsKey('speed')) { + throw Exception('Invalid JSON: Message missing "speed" key'); + } + + if (!json.containsKey('mode')) { + throw Exception('Invalid JSON: Message missing "mode" key'); + } + + if (json['text'] is! List) { + throw Exception('Invalid JSON: "text" must be a list'); + } + + final textList = json['text'] as List; + if (textList.any((element) => element == null)) { + throw Exception('Invalid JSON: "text" list cannot contain null elements'); + } + return Message( - text: List.from(json['text']), - flash: json['flash'] as bool, - marquee: json['marquee'] as bool, + text: List.from(textList), + flash: (json['flash'] as bool?) ?? false, + marquee: (json['marquee'] as bool?) ?? false, speed: Speed.fromHex( json['speed'] as String), // Using helper method for safety mode: Mode.fromHex(