google / google/json_serializable.dart

Please explain generic types deserialization

Open
#759 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

Generated code:
```dart
Response _$ResponseFromJson(
Map json,
T Function(Object json) fromJsonT,
) {
return Response()
..status = json['status'] as int
..value = fromJsonT(json['value']);
}
```
Seems like it is not fully automated for any types. It claims to provide Function for concrete types parsing.
My try:
```dart
@JsonSerializable(createToJson: false, genericArgumentFactories: true)
class Response {
final T data;
final Status status;

Response({this.data, this.status});

factory Response.fromJson(Map json) => _$ResponseFromJson(json, (jsonObject) {
switch (jsonObject) {
case User:
return User.fromJson(jsonObject) as T;
case Profile:
return Profile.fromJson(jsonObject) as T;
case StartChangeClientPhoneResponseBody:
return StartChangeClientPhoneResponseBody.fromJson(jsonObject) as T;
// primitive types, bool, etc.
default:
return jsonObject;
}
});
}
```
It throws runtime exception:
`Dart Unhandled Exception: type '_InternalLinkedHashMap' is not a subtype of type 'Profile'`

Documentation says nothing on how to handle it properly.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.