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

前端 未结 5 843
感情败类
感情败类 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 {
      static Serializer 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.

提交回复
热议问题