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

Skip unparsable Collection values #1438

Open
nrobi144 opened this issue Aug 2, 2024 · 0 comments
Open

Skip unparsable Collection values #1438

nrobi144 opened this issue Aug 2, 2024 · 0 comments

Comments

@nrobi144
Copy link

nrobi144 commented Aug 2, 2024

Given a JSONArray, where certain items can't be parsed, what's the best way to skip/filter only those elements, instead of failing to parse the whole JSONArray.

Example:

@JsonSerializable
class MyWrapperResponse(List<SomeType> object);

where parsing certain SomeTypes will fail, but the app would still like to show the other items.

Thinking of a custom converter:

class ListSkipConverter<T extends JsonSerializable> implements JsonConverter<List<T>, Map<String, dynamic>> {
  const ListSkipConverter({required this.key});

  final String key;

  @override
  List<T> fromJson(Map<String, dynamic> json) => (json[key] as List<dynamic>)
      .map((e) {
        try {
          return e.fromJson(e as Map<String, dynamic>) as T;
        } catch (e) {
          return null;
        }
      })
      .whereType<T>()
      .toList();

  @override
  Map<String, dynamic> toJson(List<T> object) => {key: object.map((e) => e.toJson()).toList()};
}

which unfortunately doesn't work as these converters are only post processors 🤔

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