google / google/json_serializable.dart

[Feature Request] provide field externally in `fromJson` method.

Open
#1,131 1 comment 6 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

# 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 json) => _$PersonFromJson(id, json);

/// Connect the generated [_$PersonToJson] function to the `toJson` method.
Map 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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.