Justin Yu
Justin Yu

Reputation: 53

How to serialize Firebase object into json using code generation in flutter

I am trying to follow the steps in this flutter doc, https://flutter.dev/docs/development/data-and-backend/json to make fireauth user object into json through code generation. Here is my code:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:json_annotation/json_annotation.dart';

part 'google_signIn_response.g.dart';

@JsonSerializable()
class GoogleSignInResponse {
  final User user;

  GoogleSignInResponse(this.user);

  factory GoogleSignInResponse.fromJson(Map<String, dynamic> json) =>
      _$GoogleSignInResponseFromJson(json);
  Map<String, dynamic> toJson() => _$GoogleSignInResponseToJson(this);
}

Here is the package I am using to do code generation:

 build_runner: ^1.11.5
 json_serializable: ^3.5.1
 json_annotation: ^3.1.1

The documentation didn't say how to do it when an custom object contains a third party package object. Can anyone help me with this? Any help will be much appreciated. Thank you!

Upvotes: 0

Views: 866

Answers (1)

Thierry
Thierry

Reputation: 8383

Did you define how to serialize the User object using explicitToJson? When set to ´true´, generated ´toJson´ methods will explicitly call toJson on nested objects.

Did you run the build_runner itself?

flutter pub run build_runner watch --delete-conflicting-outputs

On top of that, I would recommend also using the freezed package. While Freezed will not generate your typical fromJson/toJson by itself, it knowns what json_serializable is. Making a class compatible with json_serializable is very straightforward:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'model.freezed.dart';
part 'model.g.dart';

@freezed
class Model with _$Model {
  factory Model.first(String a) = First;
  factory Model.second(int b, bool c) = Second;

  factory Model.fromJson(Map<String, dynamic> json) => _$ModelFromJson(json);
}

In your class, only define the fromJson method. The toJson will also be generated.

On top of JSON serialization, you will also get immutability (which is crucial for State Management), Union/Sealed classes, copyWith method and object value == operator, and a few other gems.

Upvotes: 2

Related Questions