我有以下记录来自API
{
success: true
status: 200,
token: "...",
message: "you have logged in"
user: {id:1, first_name: "..", second_name: "..",}
}
它是一条单条记录,数据类型为_map
这是我的模型
class LoginResponseModel {
late bool success;
late int status;
late String message;
late Map<String, dynamic> user;
late String token;
LoginResponseModel(
{required this.success,
required this.status,
required this.message,
required this.user,
required this.token});
LoginResponseModel.fromjson(Map<String, dynamic> json) {
success = json['success'];
status = json['status'];
message = json['message'];
user = json['user'];
token = json['token'];
}
}
我需要将来自 API 的数据类型为 _map
var test1 = response.map((e) => LoginResponseModel.fromjson(e)).toList();
错误输出
LoginResponseModael' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'
也用过
var parsedJson = jsonDecode(response);
错误输出
type '_Map<String, dynamic>' is not a subtype of type 'String'
你说:
它是一个单个记录,数据类型为_map
由于这是一条记录,因此您不应使用
.map
来调用 response.map((e)
。
相反,只需直接使用
fromJson
:
final response = LoginResponseModal.fromjson(response);
这是一个完整的可运行片段来演示:
import 'dart:convert';
void main() {
final response = jsonDecode("""
{
"success": true,
"status": 200,
"token": "...",
"message": "you have logged in",
"user": {"id": 1, "first_name": "..", "second_name": ".."}
}
""");
final loginResponseModal = LoginResponseModal.fromjson(response);
print(loginResponseModal.message);
}
class LoginResponseModal {
late bool success;
late int status;
late String message;
late Map<String, dynamic> user;
late String token;
LoginResponseModal(
{required this.success,
required this.status,
required this.message,
required this.user,
required this.token});
LoginResponseModal.fromjson(Map<String, dynamic> json) {
success = json['success'];
status = json['status'];
message = json['message'];
user = json['user'];
token = json['token'];
}
}