Convert JSON into POJO (Object) similar to android in Flutter

前端 未结 5 844
感情败类
感情败类 2020-12-03 15:37

I\'m just trying to find a way to convert a json response (from a REST API) into POJO (As used in android) so that I can use the received data into my application as using M

5条回答
  •  星月不相逢
    2020-12-03 16:25

    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.

    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 students;
    
      School(this.name, this.maxStudentCount, this.students);
      factory School.fromJson(Map json) => _$SchoolFromJson(json);
      Map toJson() => _$SchoolToJson(this);
    }
    
    @JsonSerializable()
    class Student {
      final String name;
    
      final DateTime birthDate;
    
      Student({this.name, this.birthDate});
      factory Student.fromJson(Map json) => _$StudentFromJson(json);
      Map 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);
    }
    

    It also supports enum serialization.

    To generate the serialization code, run:

    flutter packages pub run build_runner build
    

提交回复
热议问题