I want to set a value to a field depending on another field of the same class. For example, I have classes Team and Project:
class Team {
String name;
String curator;
//etc.
}
class Project {
List<Team> teams;
List<String> curators;
//etc.
}
JSON for "Project":
{
"сommands": [
{
"name": "team 1",
"curator": "curator 1"
},
{
"name": "team 2",
"curator": "curator 2"
},
],
//etc.
}
JSON does not have a "curators" field. I need the data for this field to be taken from "teams" (or key "сommands"):
["curator 1", "curator 2"]
But field "teams" should also depend on key "сommands".
I tried doing this:
@JsonSerializable(explicitToJson: true)
class Project {
@JsonKey(name: 'сommands', fromJson: curatorsFromJson)
List<String> curators;
@JsonKey(name: 'сommands')
List<Team> currentTeams;
//etc.
}
List<String> curatorsFromJson(dynamic data) {
// logic
}
But I got the error "More than one field has the JSON key for name 'сommands'."
How can I set the value of a field depending on another field when deserializing?
You can get
curatorsfromcurrentTeams. Therefore you don't need to add jsonKey on curators.And
Teamwill be (already have the default name as key).And get data like
Project.fromJson(jsonDecode(data)).