When using json_serialiazable (https://pub.dartlang.org/packages/json_serializable), it seems the variable names need to be the same as the json ones. Am I wrong?
@JsonSerializable(nullable: false)
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
And the json will have also the 'firstName', 'lastName' and 'dateOfBirth' parameters.
Let say, I prefer to use 'final String first' instead of 'firstName', but still want 'firstName' read from the json be mapped to 'first'. Is it possible?
I know there is the manual way, but if I still can use that way, I would like to know how?
Thanks!
You can add an annotation to customize
@JsonKey(name: 'firstName')
final String first;
See also https://github.com/dart-lang/json_serializable/blob/master/json_annotation/lib/src/json_key.dart which supports various settings for serialization and deserialization.
The json_annotation package has several more annotations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With