flutter 泛型_Flutter-如何将嵌套的json解析为具有泛型的类?

本文探讨如何将包含令牌的嵌套JSON解析为具有泛型的类。作者遇到的问题是无法直接从JSON创建`T.fromJson()`。解决方案是使用面向对象编程,为每种响应类型创建子类,并在基类中提供工厂构造函数以方便使用。
摘要由CSDN通过智能技术生成

I'm wondering how can I parse a nested json to a class with generic types. My intention is to wrap responses from the backend (like loginRespose that contains a token) with a code and a message

I have

class BaseResponse{

int code;

String message;

T responseObject;

BaseResponse.fromJson(Map parsedJson)

: code = parsedJson['Code'],

message = parsedJson['Message'],

responseObject = T.fromJson(parsedJson['ResponseObject']); //This is what I'd like to do

}

Obviously the last line throws an error because T doesn't has a named constructor "fromJson".

I tried adding some restrictions to the Type but I didn't find any solutions. Do you have any idea on how to pull this off?

解决方案

You can't do such thing, at least not in flutter. As dart:mirror is disabled and there's no interface for classes constructors.

You'll have to take a different route.

I'll recommend using POO instead. You would here give up on deserializing responseObject from your BaseResponse. And then have subclass of BaseResponse handles this deserialization

Typically you'd have one subclass per type:

class IntResponse extends BaseResponse {

IntResponse.fromJson(Map json) : super._fromJson(json) {

this.responseObject = int.parse(json["Hello"]);

}

}

You can then hide this mess away by adding a custom factory constructor on BaseResponse to make it more convenient to use.

class BaseResponse {

int code;

String message;

T responseObject;

BaseResponse._fromJson(Map parsedJson)

: code = parsedJson['Code'],

message = parsedJson['Message'];

factory BaseResponse.fromJson(Map json) {

if (T == int) {

return IntResponse.fromJson(json) as BaseResponse;

}

throw UnimplementedError();

}

}

Then either instantiate the wanted type directly, or use the factory constructor :

final BaseResponse foo = BaseResponse.fromJson({"Hello": "42", "Code": 42, "Message": "World"});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值