Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
AntoniPochopien opened this issue Dec 13, 2024 · 0 comments
Open

Comments

@AntoniPochopien
Copy link

AntoniPochopien commented Dec 13, 2024

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant