Convert JSON into POJO (Object) similar to android in Flutter. json_serializable isn’t that well documented, but it does exactly what you want, is easier to use and requires less boilerplate than built_value, especially when it comes to arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import 'package:json_annotation/json_annotation.dart'; import 'dart:convert'; part 'school.g.dart'; @JsonSerializable() class School { final String name; final int maxStudentCount; final List<Student> students; School(this.name, this.maxStudentCount, this.students); factory School.fromJson(Map<String, dynamic> json) => _$SchoolFromJson(json); Map<String, dynamic> toJson() => _$SchoolToJson(this); } @JsonSerializable() class Student { final String name; final DateTime birthDate; Student({this.name, this.birthDate}); factory Student.fromJson(Map<String, dynamic> json) => _$StudentFromJson(json); Map<String, dynamic> toJson() => _$StudentToJson(this); } test() { String jsonString = '''{ "name":"Trump University", "maxStudentCount":9999, "students":[ { "name":"Peter Parker", "birthDate":"1999-01-01T00:00:00.000Z" } ] }'''; final decodedJson = json.decode(jsonString); final school = School.fromJson(decodedJson); assert(school.students.length == 1); } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.