Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can variable name be different than the json ones?

Tags:

json

flutter

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!

like image 507
David Avatar asked Feb 01 '26 23:02

David


1 Answers

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.

like image 189
Günter Zöchbauer Avatar answered Feb 03 '26 17:02

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!