JsonSerializable. Custom function for field, dependencing other field of current class

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?

Upvotes: 0

Views: 74

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

You can get curators from currentTeams. Therefore you don't need to add jsonKey on curators.

@JsonSerializable(explicitToJson: true)
class Project {
  final List<String> curators;

  @JsonKey(name: 'сommands')
  final List<Team> currentTeams;

  Project({
    required this.currentTeams,
  }) : curators = currentTeams.map((e) => e.curator).toList();

  factory Project.fromJson(Map<String, dynamic> json) =>
      _$ProjectFromJson(json);

  Map<String, dynamic> toJson() => _$ProjectToJson(this);
}

And Team will be (already have the default name as key).

@JsonSerializable()
class Team {
  String name;  
  String curator;

  Team({
    required this.name,
    required this.curator,
  });

  factory Team.fromJson(Map<String, dynamic> json) => _$TeamFromJson(json);

  Map<String, dynamic> toJson() => _$TeamToJson(this);
}

And get data like Project.fromJson(jsonDecode(data)).

Upvotes: -1

Related Questions