Is it possible to use json_serializable and have different key names for same field for toJson and fromJson.
ex json-data:
{
"idUser": 123,
/// some other fields
}
incoming json_data from another APIs
{
"id" : 123,
/// some other fields
}
@JsonSerializable()
class Id extends INetworkModel<Id> {
Id(this.idUser);
final int? idUser;
@override
Id fromJson(Map<String, dynamic> json) => _$IdFromJson(json);
@override
Map<String, dynamic>? toJson() => _$IdToJson(this);
}
for that particular id field, I want to map it as idUser for toJson and id as fromJson.
based on what I saw for json_serializable docs it’s possible to manipulate field values with custom toJson and fromJson methods but didn’t see any other option to manipulate key names in JSON based on the method.
I would be very glad if someone enlightens me thanks ahead!
2
Answers
An alternative approach to having 2 sources for the same property:
Parse both as nullable, and have a getter to retrieve the value. Something like:
Not recommended, however you can do
Go to
yourfile.g.dart