Skip to content

[Feature Request] provide field externally in fromJson method. #1131

Open
@matanshukry

Description

@matanshukry

Proposal

Mark a field that should be used as an input in toJson, rather than read from the jsonMap.

Example:

@JsonSerializable()
class Person {
  @JsonKey(ignore: true, externalFromJson: true)
  final String id;

  final String firstName;

  Person({required this.id, required this.firstName});

  /// Connect the generated [_$PersonFromJson] function to the `fromJson`
  /// factory.
  factory Person.fromJson(String id, Map<String, dynamic> json) => _$PersonFromJson(id, json);

  /// Connect the generated [_$PersonToJson] function to the `toJson` method.
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

The generatd code of fromJson would then use the argument rather than attempting to read it from the json map.

Use Case

Firebase documents. Each document in firebase has an id, and it's saved externally from the json. Right now there are various options to overcome this, but they all involve some change to the way the data should be represented, only to conform to the libraries we use - which shouldn't be true.

to clarify, the changes I'm talking about is changing the type of the id. Either removing final, adding late, changing to nullable String?, etc.

Assuming we're using Firebase and we have a document

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