toJson method
Serializes this model instance to a JSON map.
Converts all non-null field values to their JSON representation. Fields with null values are excluded from the output. Additionally, ID fields (fields ending with 'id' except 'statusId') with a value of 0 are also excluded, as they represent unset foreign key references.
Returns:
A Map<String, dynamic> representing the model in JSON format, ready
for transmission to a server or storage.
Example:
final user = UserModel();
user['name'] = 'John Doe';
user['age'] = 30;
final json = user.toJson(); // {'name': 'John Doe', 'age': 30}
Implementation
@override
Map<String, dynamic> toJson() {
final Map<String, dynamic> json = <String, dynamic>{};
for (final field in fields) {
if (field.fieldName.toLowerCase().endsWith('id') &&
field.fieldName != 'statusId') {
if (field.value == 0) {
json.remove(field.fieldName);
continue;
}
}
if (field.rawValue != null) {
final fieldValue = field.toJson();
if (fieldValue != null) {
json[field.fieldName] = fieldValue;
}
}
}
return json;
}