Skip to content

Instantly share code, notes, and snippets.

@wisnuwiry
Created February 3, 2022 12:23
Show Gist options
  • Save wisnuwiry/fdfa9bb6f56659f8a65957a628145461 to your computer and use it in GitHub Desktop.
Save wisnuwiry/fdfa9bb6f56659f8a65957a628145461 to your computer and use it in GitHub Desktop.
Example of Flutter/Dart Dynamic JSON Key Parsing
const rawData = {
'status': 'Success',
'data': {
'2022-10-1': true,
'2022-10-2': false,
'2022-10-3': true,
'2022-10-4': false,
}
};
void main() {
final jsonParseResult = Model1.fromJson(rawData);
print('STATUS: ${jsonParseResult.status}');
print('DATA:');
for (final item in jsonParseResult.data){
print('Model2(field1: ${item.field1}, field2: ${item.field2})');
}
}
class Model1 {
const Model1({
required this.data,
required this.status,
});
final List<Model2> data;
final String status;
factory Model1.fromJson(Map<String, dynamic> json) {
final _data = <Model2>[];
if (json['data'] != null && json['data'] is Map) {
for (final element in (json['data'] as Map).entries) {
_data.add(Model2.fromJson(element as MapEntry<String, dynamic>));
}
}
return Model1(
data: _data,
status: json['status'] ?? 'failure',
);
}
}
class Model2 {
const Model2({
required this.field1,
required this.field2,
});
final String field1;
final bool field2;
factory Model2.fromJson(MapEntry<String, dynamic> json) {
return Model2(
field1: json.key,
field2: json.value,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment