Skip to content

Nested Generics #202

Closed
Closed
@pythoneer

Description

@pythoneer

i think this his highly related to this issue

but i have some trouble using it for my needs. I either use it wrong or it is currently not possible.

this is an example of what i want to parse

{
  "status": "success",
  "message": null,
  "code": 0,
  "data": {
    "timestamp": 0,
    "result": [
      {
        "id": 409,
        "active": true,
        "accessToken": "12345_abc",
      }
    ]
  }
}

and here the corresponding classes

@JsonSerializable()
class WsResponse<T> extends Object with _$WsResponseSerializerMixin<T> {

  String status;
  String message;
  int code;
  @JsonKey(fromJson: _dataFromJson, toJson: _dataToJson)
  WsData<T> data;

  WsResponse({this.status, this.message, this.code, this.data});

  factory WsResponse.fromJson(Map<String, dynamic> json) => _$WsResponseFromJson<T>(json);
}

here i have an outer "class" with status message and code that works like every ordinary class.

@JsonSerializable()
class WsData<T> extends Object with _$WsDataSerializerMixin<T> {
  int timestamp;
  @JsonKey(fromJson: _resultFromJson, toJson: _resultToJson)
  List<T> result;

  WsData({this.timestamp, this.result});

  factory WsData.fromJson(Map<String, dynamic> json) => _$WsDataFromJson<T>(json);
}
@JsonSerializable()
class WsLogin extends Object with _$WsLoginSerializerMixin {
  int id;
  bool active;

  String accessToken;

  WsLogin({this.id, this.active, this.accessToken,});

  factory WsLogin.fromJson(Map<String, dynamic> json) => _$WsLoginFromJson(json);
}

I omitted the fromJson etc. definitions because i don't know how to express them right either (may be the part where i am wrong)

but if i try _dataFromJson for example

WsData<T> _dataFromJson<T>(Map<String, dynamic> input) {
  return input['data'] as WsData<T>;
}

i get an error with

[SEVERE] json_serializable on lib/webservice/webservice.dart:
Error running JsonSerializableGenerator
Error with `@JsonKey` on `data`. The `fromJson` function `_dataFromJson` return type `WsData<T>` is not compatible with field type `WsData<T>`.
package:crewlove/webservice/webservice.dart:31:13
  WsData<T> data;
            ^^^^

which is surprising for me at first. Omitting the @JsonKey annotations does not help either as i think its necessary for generics. But i don't know how to express my intent here.

My intent is to use it like this

var wsLoginResp = new WsResponse<WsLogin>.fromJson(json.decode(resp));  

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