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

前端 未结 5 825
感情败类
感情败类 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:18

    This can be done using built_value. Detailed documentation is available in this link.

    You just have to write some boilerplate code and run this command flutter packages pub run build_runner build.

    Below is a sample class like POJO.

    import 'package:built_value/built_value.dart';
    import 'package:built_value/serializer.dart';
    
    part 'auth.g.dart';
    
    abstract class Auth implements Built<Auth, AuthBuilder> {
      static Serializer<Auth> get serializer => _$authSerializer;
    
      String get currentServerTime;
      int get defaultOrganization;
      String get tokenExpiryTimeInMs;
      bool get rememberMe;
      int get failedLoginAttempts;
      int get userId;
      String get status;
      String get token;
    
      Auth._();
      factory Auth([updates(AuthBuilder b)]) = _$Auth;
    }
    

    Below is the Serializer class:

    library serializers;
    
    import 'package:built_value/serializer.dart';
    import 'package:built_value/standard_json_plugin.dart';
    import 'auth/auth.dart';
    
    part 'serializers.g.dart';
    
    @SerializersFor(const [
      Auth,
    ])
    
    Serializers serializers = _$serializers;
    
    Serializers standardSerializers =
    (serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();
    

    Below is the code where conversion from JSON to Object takes place.

    Auth auth = standardSerializers.deserializeWith(
            Auth.serializer, json.decode(res.body)['user']);
    

    Hope this helps.

    0 讨论(0)
  • 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<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);
    }
    

    It also supports enum serialization.

    To generate the serialization code, run:

    flutter packages pub run build_runner build
    
    0 讨论(0)
  • Android Studio plugin: https://plugins.jetbrains.com/plugin/12562-jsontodart-json-to-dart-

    Online: https://javiercbk.github.io/json_to_dart/

    Manually parse: https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51

    Generate Dart classes from JSON

    Convert JSON to Dart class

    Generate Dart class from JSON or JSON-Schema.

    0 讨论(0)
  • 2020-12-03 16:28

    Please take a look at this post to get the best option for your goal

    0 讨论(0)
  • 2020-12-03 16:35

    SO, after some tries with the json_serializable library, I came up with my own solution and it doesnt require any external library at all and works like a charm. This way i had to write less boilerplate code and i think is a clean way to do this.

    Here's how to make the model

    class SideMenuRes {
    final int status;
    final String message;
    final List<SideMenuDatum> sideMenuData;
    
    SideMenuRes({this.status, this.message, this.sideMenuData});
    factory SideMenuRes.fromJson(Map json) {
      return SideMenuRes(
        status: json['status'],
        message: json['message'],
        sideMenuData: json['status'] == 200 ? (json['data'] as List).map((i) => new 
      SideMenuDatum.fromJson(i)).toList() : null,
      );
    }
    }
    
    class SideMenuDatum {
    final Menu menu;
    SideMenuDatum({this.menu});
    factory SideMenuDatum.fromJson(Map json) {
      return SideMenuDatum(
        menu: Menu.fromJson(json['menu']),
      );
    }
    }
    
    class Menu {
    final String megamenu_id;
    final String language_id;
    final String title;
    final String description;
    final List<SubMenu> subMenu;
    
    Menu({this.megamenu_id, this.language_id, this.title, this.description, this.subMenu});
    factory Menu.fromJson(Map json) {
      return Menu(
          megamenu_id: json['megamenu_id'],
          language_id: json['language_id'],
          title: json['title'],
          description: json['description'],
          subMenu: json['submenu'] != null ? (json['submenu'] as List).map((i) => new SubMenu.fromJson(i)).toList() : null
      );
    }
    }
    
    class SubMenu {
    final Zero zero;
    final List<SubSubMenu> subSubMenu;
    
    SubMenu({this.zero, this.subSubMenu});
    factory SubMenu.fromJson(Map json) {
      return SubMenu(
          zero: Zero.fromJson(json['0']),
          subSubMenu: (json['subsubmenu'] as List).map((i) => new SubSubMenu.fromJson(i)).toList()
      );
    }
    }
    
    class Zero {
    final Info info;
    Zero({this.info});
    factory Zero.fromJson(Map json) {
      return Zero(
        info: Info.fromJson(json['info']),
      );
      }
     }
    
    class SubSubMenu {
    final InfoSub infoSub;
    SubSubMenu({this.infoSub});
    
    factory SubSubMenu.fromJson(Map json) {
      return SubSubMenu(
          infoSub: InfoSub.fromJson(json['infosub'])
      );
    }
    }
    
    class InfoSub {
    final String megamenu_id;
    final String language_id;
    final String title;
    final String description;
    
    InfoSub({this.megamenu_id, this.language_id, this.title, this.description});
    factory InfoSub.fromJson(Map json) {
    return InfoSub(
        megamenu_id: json['megamenu_id'],
        language_id: json['language_id'],
        title: json['title'],
        description: json['description']
      );
     }
    }
    
    class Info {
     final String megamenu_id;
     final String language_id;
    final String title;
    final String description;
    
    Info({this.megamenu_id, this.language_id, this.title, this.description});
    factory Info.fromJson(Map json) {
    return Info(
        megamenu_id: json['megamenu_id'],
        language_id: json['language_id'],
        title: json['title'],
        description: json['description']
      );
     }
    }
    

    And calling it like this

    SubMenuRes subMenuRes = SubMenuRes.fromJson(response.data);
    

    That's it!

    0 讨论(0)
提交回复
热议问题