Created
July 3, 2023 16:40
-
-
Save qisantanu/98a415e30137d415fb10b1fba228060e to your computer and use it in GitHub Desktop.
JSON and serialization in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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