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?
Asked
Active
Viewed 5,384 times
2 Answers
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
-
1Multiple JsonKey doesn't work for me. – NothingBox Oct 08 '22 at 17:22
-
Multiple JsonKey doesn't work for me neither – Lubbo Jul 20 '23 at 13:30
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
-
1
-
it works both ways. '??=' is the formatted way but '?? =' works fine too – Adnan Jun 20 '23 at 20:22
-
1Interesting why it doesn't work for me. When I write them separately it detects it as a syntax error. – Lachezar Todorov Jun 21 '23 at 09:28
-
I've just tested this on dartpad, and looks like you're right. I apologize for commenting without testing, I'll update my answer – Adnan Jun 21 '23 at 16:16