Skip to content

Issue with Parsing Nested JSON Fields with the Same Key Name in #1463

Open
@AntoniPochopien

Description

@AntoniPochopien

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

  1. Is there a proper way to handle such cases where multiple values need to be extracted from a single nested object?
  2. 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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions