toJson method
Converts the object to a JSON representation.
Implementation
@override
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
bool isNonEmpty(dynamic val) {
if (val == null) return false;
if (val is List && val.isEmpty) return false;
if (val is Map && val.isEmpty) return false;
return true;
}
void addField(String key, dynamic field) {
if (field == null) return;
if (!(field is FhirBase? || field is List<FhirBase>?)) {
throw ArgumentError('"field" must be a FhirBase type');
}
if (field is PrimitiveType) {
final fieldMap = field.toJson();
final val = fieldMap['value'];
final ext = fieldMap['_value'];
final hasVal = isNonEmpty(val);
final hasExt = isNonEmpty(ext);
if (hasVal) json[key] = val;
if (hasExt) json['_$key'] = ext;
} else if (field is List<FhirBase>) {
if (field.isEmpty) return;
final isPrimitive = field.first is PrimitiveType;
final tempList = <dynamic>[];
final tempExtensions = <dynamic>[];
for (final e in field) {
final itemMap = e.toJson();
if (!isNonEmpty(itemMap)) {
continue;
}
if (isPrimitive) {
final v = itemMap['value'];
final x = itemMap['_value'];
tempList.add(v);
tempExtensions.add(x);
} else {
tempList.add(itemMap);
}
}
if (tempList.isEmpty) return;
if (isPrimitive) {
final hasAnyValues = tempList.any((v) => v != null);
if (hasAnyValues) {
json[key] = tempList;
}
final anyExt = tempExtensions.any(isNonEmpty);
if (anyExt) {
json['_$key'] = tempExtensions;
}
} else {
json[key] = tempList;
}
} else if (field is FhirBase) {
final subMap = field.toJson();
if (isNonEmpty(subMap)) {
json[key] = subMap;
}
}
}
addField(
'id',
id,
);
addField(
'extension',
extension_,
);
addField(
'modifierExtension',
modifierExtension,
);
addField(
'type',
type,
);
addField(
'value',
value,
);
addField(
'baseCitation',
baseCitation,
);
return json;
}