Home > database >  Flutter json_serializable what if key can have different names
Flutter json_serializable what if key can have different names

Time:12-09

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?

CodePudding user response:

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

CodePudding user response:

You could just modify your file and replace the old object names. For example you can do it with sed

sed -i 's/{OLD_TERM}/{NEW_TERM}/g' {file}
  • Related