Skip to content

Instantly share code, notes, and snippets.

@qisantanu
Created July 3, 2023 16:40
Show Gist options
  • Save qisantanu/98a415e30137d415fb10b1fba228060e to your computer and use it in GitHub Desktop.
Save qisantanu/98a415e30137d415fb10b1fba228060e to your computer and use it in GitHub Desktop.
JSON and serialization in Dart
import 'dart:convert';
import 'dart:core';
void main() {
var x = {
'data': [
{'id': 1, 'attributes': {'name': "R"}}, {'id': 2, 'attributes': {'name': "S"}}
]
};
Fm.fromJson(x);
}
class Fm {
final List<Data> data;
Fm({required this.data});
factory Fm.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['data'] as List;
// print(list.runtimeType);
List<Data> dataList = list.map((i) => Data.fromJson(i)).toList();
//print(dataList);
return Fm(data: dataList);
}
}
class Data {
final int id;
final Attributes attributes;
Data({
required this.id,
required this.attributes,
});
factory Data.fromJson(Map<String, dynamic> parsedJson) {
print(parsedJson['id']);
var attrJson = Attributes.fromJson(parsedJson['attributes']);
return Data(
id: parsedJson['id'],
attributes: attrJson,
);
}
}
class Attributes {
final String name;
Attributes({required this.name});
factory Attributes.fromJson(Map<String, dynamic> parsedJson) {
print(parsedJson['name']);
return Attributes(
name: parsedJson['name'],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment