generateModel function
Generates a Dart model from a JSON file.
Supports:
- Nested objects → nested classes
- Safe parsing via ParsingHelper
rootClassName is the name of the main model class.
json is the decoded JSON map.
sourcePath is the file path of the input JSON.
Implementation
String generateModel(
String rootClassName,
Map<String, dynamic> json,
String sourcePath,
) {
final classes = <GeneratedClass>[];
void process(String className, Map<String, dynamic> json) {
classes.add(GeneratedClass(className, json));
json.forEach((key, value) {
if (value is Map<String, dynamic>) {
final nestedName = _capitalize(_toCamelCase(key));
process(nestedName, value);
}
});
}
process(rootClassName, json);
final buffer = StringBuffer();
// ✅ Add ParsingHelper import
buffer.writeln("import 'package:your_project/utils/parsing_helper.dart';\n");
for (final cls in classes.reversed) {
buffer.writeln(_buildClass(cls.name, cls.json));
}
final file = File(sourcePath);
final dir = file.parent.path;
final outputPath = '$dir/${rootClassName.toLowerCase()}.dart';
File(outputPath).writeAsStringSync(buffer.toString());
print("✅ Generated at: $outputPath");
return outputPath;
}