Flutter json_serializable what if key can have different names

732

Hey what I think you can do is to provide multiple json key annotations to the same field in your model.

@JsonSerializable()
class Person {

  @JsonKey(name: 'name') 
  @JsonKey(name:'first_name')
  final String firstName, lastName;

  final DateTime? dateOfBirth;

  Person({required this.firstName, required this.lastName, this.dateOfBirth});

  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

alternatively you can give the json key annotation an explicit fromJson parameter a function to fully control how this field gets deserialized

Share:
732
ambstuc
Author by

ambstuc

Updated on December 02, 2022

Comments

  • ambstuc
    ambstuc over 1 year

    I am using json_serializable in Flutter to store a class in a file and read back from it. I am not posting the original class here for simplicity, but the principle is that half way through writing the app I decided that I wanted to change the variable name "aStupidName" to "name". How can I advise the code generation utility to assign the JSON value with the key "aStupidName", if it exists in the JSON, to the variable "name", but if the key "name" exists to assign this to the variable instead, i.e. in newer versions of the file?