Description
Problem Description:
I am encountering an issue with parsing nested JSON fields using json_serializable in Dart. Below is the JSON structure I am receiving:
{
is_admin: false,
profiles: {
id: f13b4125-30bf-4dd2-8331-e1a7066bdd1b,
username: antek2
}
}
I am trying to extract both the id and username fields from the nested profiles object using the following freezed class:
@freezed
class GroupMember with _$GroupMember {
const GroupMember._();
const factory GroupMember({
@JsonKey(name: 'profiles') @_IdConverter() required String id,
@JsonKey(name: 'profiles') @_UsernameConverter() required String username,
@JsonKey(name: 'is_admin') required bool isAdmin,
}) = _GroupMember;
factory GroupMember.fromJson(Map<String, dynamic> json) =>
_$GroupMemberFromJson(json);
}
he problem arises when I attempt to define two fields (id and username) with the same @ JsonKey(name: 'profiles') annotation. This results in the following error:
More than one field has the JSON key for name "profiles".
Questions
- Is there a proper way to handle such cases where multiple values need to be extracted from a single nested object?
- Would this be a feasible update for the json_serializable package to support such scenarios? If so, I would be happy to contribute and attempt a fix for this functionality.
Additional Context
While I have implemented custom converters (_IdConverter and _UsernameConverter) to handle the extraction, the limitation of having only one field with the same JSON key name makes this approach impractical. I am looking for a cleaner and more intuitive solution.
Let me know your thoughts on this issue. Any guidance or recommendations for best practices would be greatly appreciated!