在Flutter中将json响应转换为对象时出现问题

时间:2020-07-07 17:46:51

标签: json api flutter

首先,所有对我的“恩宠”感到抱歉... 我正在尝试使用Flutter中的http包使用自己的API方法。 我可以从API获得响应,但是在尝试将响应(json)映射到名为APILoginResponse的自定义对象时遇到了麻烦。

我正在这样调用API方法:

APILoginResponse apiLogin = await api.apiLogin();

但是我遇到了运行时错误“动态不是AccessToken的子类型”。

这是我的API登录方法:

Future<APILoginResponse> apiLogin() async {
  final http.Response response = await http.post(
    api_end_point + '/api/Auth/login',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(
        <String, String>{'userName': api_user, 'password': api_password}),
  );
  if (response.statusCode == 200) {
    return APILoginResponse.fromJson(json.decode(response.body));
  } else {
    throw Exception('Error en login de la API');
  }
}

...这是我的APILoginResponse对象:

class APILoginResponse {
  final AccessToken accessToken;
  final String refreshToken;

  APILoginResponse({this.accessToken, this.refreshToken});

  factory APILoginResponse.fromJson(Map<String, dynamic> json) {
    return APILoginResponse(
      accessToken: json['accessToken'],
      refreshToken: json['refreshToken'],
    );
  }
}

class AccessToken {
  String token;
  int expiresIn;
}

错误所在:

accessToken: json['accessToken']

内部APILoginResponse类。

这是我的json响应:

{
  "accessToken": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiIiLCJzdWIiOiJib3N0b25jcmVkX2NsaWVudGVzIiwianRpIjoiZjBkMzY0ZDMtMmRkNS00NzkzLWE5ZTktMzY1YzJmODNiYmI3IiwiaWF0IjoxNTk0MTMxODAwLCJyb2wiOiJhcGlfYWNjZXNzIiwiaWQiOiIyMzg3YTMzZi1hYzE5LTRhMzYtODcyZC04MTE3MzExZDFjY2IiLCJuYmYiOjE1OTQxMzE3OTksImV4cCI6MTU5NDEzMjM5OSwiaXNzIjoid2ViQXBpIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzMTcvLyJ9.PqCPkVct4e4duWFEr63fALZ0h_0x25vsV_GBx336Apw",
    "expiresIn": 600
  },
  "refreshToken": "W6wyiw9xYuC2UaJmyCOYujKIZTs0jAscnfcWTrEyVIk="
}

任何对此的帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

如果您确定返回值是AccessToken,则可以尝试以下操作:

  factory APILoginResponse.fromJson(Map<String, dynamic> json) {
   return APILoginResponse(
   accessToken: (json['accessToken'] as Map<String,dynamic>) as AccessToken ?? null,
   refreshToken: json['refreshToken'],
   );
 }

将您的AccessToken类更改为此:

class AccessToken {
   final Map<String,dynamic> tokenData;
   AccessToken(tokenData)
}

答案 1 :(得分:0)

好吧,我认为@ P4yam答案是正确的,但是我一遍又一遍地遇到相同的错误,因此我如下更改了我的APILoginResponse类:

class APILoginResponse {
  AccessToken accessToken;
  String refreshToken;

  APILoginResponse({this.accessToken, this.refreshToken});

  APILoginResponse.fromJson(Map<String, dynamic> json) {
    accessToken = json['accessToken'] != null
        ? new AccessToken.fromJson(json['accessToken'])
        : null;
    refreshToken = json['refreshToken'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.accessToken != null) {
      data['accessToken'] = this.accessToken.toJson();
    }
    data['refreshToken'] = this.refreshToken;
    return data;
  }
}

class AccessToken {
  String token;
  int expiresIn;

  AccessToken({this.token, this.expiresIn});

  AccessToken.fromJson(Map<String, dynamic> json) {
    token = json['token'];
    expiresIn = json['expiresIn'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['token'] = this.token;
    data['expiresIn'] = this.expiresIn;
    return data;
  }
}

现在一切正常!谢谢!