Skip to content

Allow extra non-serializable fields to be passed into fromJson and ignored in toJson #780

Open
@hacker1024

Description

@hacker1024

I have a User object, which is deserialized from JSON in an API response:

@JsonSerializable()
class User {
  final String authToken;
  final String username;
  final String profilePictureUrl;

  const User({
    required this.authToken,
    required this.username,
    required this.profilePictureUrl,
  });

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  
  static Future<User> login(String email, String password) async {
    final responseJson = await api.login(email, password);
    return User.fromJson(responseJson);
  }
}

Occasionally, the authToken used in API calls may be invalidated. If this happens, I need to reauthenticate the user.
To do this, I need the user's credentials. Ideally, I'd like to store these credentials in the User object when it's created so I can use them later. As the credentials are not included in the API response, I'd love to do something like this:

@JsonSerializable()
class User {
  @JsonKey(extra: true)
  final String email;
  @JsonKey(extra: true)
  final String password;

  final String authToken;
  final String username;
  final String profilePictureUrl;

  const User({
    required this.email,
    required this.password,
    required this.authToken,
    required this.username,
    required this.profilePictureUrl,
  });

  factory User.fromJson(
    Map<String, dynamic> json, {
    required String email,
    required String password,
  }) =>
      _$UserFromJson(
        json,
        email: email,
        password: password,
      );

  static Future<User> login(String email, String password) async {
    final responseJson = await api.login(email, password);
    return User.fromJson(
      responseJson,
      email: email,
      password: password,
    );
  }
}

As you can see, the use of a JsonKey argument like 'extra' would allow the additional values to be passed to the generated deserialisation function, which in turn would pass them through to the constructor unmodified.

Upon serialisation, the extra fields can be ignored, as they're application-specific and not part of the API spec.

My SDK version, as requested
Flutter 1.26.0-1.0.pre • channel dev • https://github.com/flutter/flutter.git
Framework • revision 63062a6443 (3 weeks ago) • 2020-12-13 23:19:13 +0800
Engine • revision 4797b06652
Tools • Dart 2.12.0 (build 2.12.0-141.0.dev)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions