7

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?

ambstuc
  • 71
  • 1
  • 2

2 Answers2

7

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

Hadi Hassan
  • 331
  • 1
  • 3
2

here is what you can do:

factory Person.fromJson(Map<String, dynamic> json) {
  json['name'] ??= json['aStupidName'];
  
  return _$PersonFromJson(json);
}

basically, before the json conversion we're transferring the data of aStupidName to name key.

Adnan
  • 906
  • 13
  • 30