I could not find an example of how to read in a list of JSON objects from a file using the Flutter packages: json_annotation and json_serializable. After a while I figured the way to do it. This post shows an example of automating JSON de-serialization of a JSON file that looks like the following:
[ { "code": "NED", "fullname": "North East Down (local)", }, { "code": "ECEF", "fullname": "Earth Centered Earth Fixed (ECEF)", }, { "code": "LLA", "fullname": "WGS 84", } ]
Install the Flutter packages Json_serializable and Json_annotation
In a Terminal, type in the following:
$ cd /path/to/the/root/of/flutter/project/
$ flutter pub add json_annotation
$ flutter pub add json_serializable
Code the model class dart file
- In a text editor, create the model class dart file, e.g. cs_model.dart.
- Type in the following:
import 'package:json_annotation/json_annotation.dart'; // Part file to be auto generated part 'cs_model.g.dart'; @JsonSerializable() class APICoordSysQuery { // Factory method to load in the list of JSON objects factory APICoordSysQuery.fromJson(List<dynamic> parsedJson){ List<APICoordSys> csList = List<APICoordSys>.empty(); csList = parsedJson.map ( (e) => APICoordSys.fromJson(e)).toList(); return APICoordSysQuery( csList: csList, ); } // To be auto generated by the Json_serializable package Map<String, dynamic> toJson() => _$APICoordSysQueryToJson(this); @JsonKey(name: 'csList') List<APICoordSys> csList; APICoordSysQuery({ required this.csList }); } @JsonSerializable() class APICoordSys { // Factory method to deserialize a JSON object to be auto generated factory APICoordSys.fromJson(Map<String, dynamic> json) => _$APICoordSysFromJson(json); // Factory method to serialize a JSON Object to be auto generated Map<String, dynamic> toJson() => _$APICoordSysToJson(this); @JsonKey(name: 'code') String code; @JsonKey(name: 'fullname') String fullName; // Constructor APICoordSys({ required this.code, required this.fullName }); }
Generate the .part file
- In a Terminal, run the following:
$ cd /path/to/flutter/root/project/
$ dart run build_runner build
Processing messages appear and the cs_model.part.g.dart file is generated.
Now you should be able to load in a list of JSON objects in Flutter.
No comments:
Post a Comment