Flutter: Generating JSON-Serialization
Flutter has a library for generating (de)serialization of json-data.
You need following development(!)-dependencies:
dev_dependencies:
# Your other dev_dependencies here
build_runner: <latest_version>
json_serializable: <latest_version>
Your task is to write the class that will hold the data on your own and annotate it with @JsonSerializable and optionally give hints about the fields using @JsonKey . Additionally you need to write a set-factory 'fromJson(...)' and toJson()-method. (see below)
@JsonSerializable()
class Song {
Song(this.name, this.id);
@JsonKey(name: 'ID')
int id;
@JsonKey(name: 'Name')
String name;
@JsonKey(name: 'Upvotes')
int upvotes;
@JsonKey(name: 'YoutubeUrls')
List<String> youtubeUrls;
@JsonKey(name: 'Lyrics')
String lyrics;
factory Song.fromJson(Map<String, dynamic> json) => _$SongFromJson(json);
Map<String, dynamic> toJson() => _$SongToJson(this);
static List<Song> fromList(List<dynamic> jsonSongList) =>
jsonSongList.map((e) => Song.fromJson(e)).toList();
}
After specifying this you can call the generator like this:
flutter pub run build_runner build
This will generate a fill song.g.dart in which those _$SongToJson- and _$SongFromJson-Methods are generated automatically:
Song _$SongFromJson(Map<String, dynamic> json) {
return Song(
json['Name'] as String,
json['ID'] as int,
)
..upvotes = json['Upvotes'] as int
..youtubeUrls =
(json['YoutubeUrls'] as List)?.map((e) => e as String)?.toList()
..lyrics = json['Lyrics'] as String;
}
Map<String, dynamic> _$SongToJson(Song instance) => <String, dynamic>{
'ID': instance.id,
'Name': instance.name,
'Upvotes': instance.upvotes,
'YoutubeUrls': instance.youtubeUrls,
'Lyrics': instance.lyrics,
};
References:
https://flutter.dev/docs/development/data-and-backend/json