问题描述
我是 flutter dev 的新手,正在尝试将模型转换为 json 字符串以传递给 api 调用。
当我尝试使用 RegistrationRequest.ToJson 函数时,出现此错误
type '_InternalLinkedHashMap<String,dynamic>' is not a subtype of type 'String'
我认为它无法正确转换 userImages 列表,并且不太确定如何进行转换。任何帮助将不胜感激
这里是我调用函数的地方
var serialisedBodycom = RegistrationRequest.toJson();
var serialisedBody = jsonEncode(serialisedBodycom);
我有一个模型叫做 注册请求
import 'UserGender.dart';
import 'UserImage.dart';
class RegistrationRequest {
String email;
String password;
String msisdn;
UserGender gender;
UserGender matchGender;
List<UserImage> userImages;
RegistrationRequest(
{this.email,this.password,this.msisdn,this.gender,this.matchGender,this.userImages});
RegistrationRequest.Empty();
RegistrationRequest.fromJson(Map<String,dynamic> json)
: email = json['email'],password = json['password'],msisdn = json['msisdn'],gender = json['gender'],matchGender = json['matchGender'],userImages = json['userImages'];
Map<String,dynamic> toJson() {
return {
'email': email ?? '','password': password ?? '','MSISDN': msisdn ?? '','Gender': gender ?? UserGender.Unknown,'MatchGender': matchGender ?? UserGender.Unknown,'UserImages': userImages ?? new List<UserImage>()
};
}
}
其中包含一个 UserImage 列表
class UserImage {
String base64;
String fileName;
bool isMainProfilePicture;
String contentType;
UserImage(
this.base64,this.fileName,this.isMainProfilePicture,this.contentType);
UserImage.Empty();
UserImage.fromJson(Map<dynamic,dynamic> json)
: base64 = json['base64'],fileName = json['fileName'],isMainProfilePicture = json['isMainProfilePicture'],contentType = json['contentType'];
Map<dynamic,dynamic> toJson() => {
'base64': base64,'fileName': fileName,'isMainProfilePicture': isMainProfilePicture,'contentType': contentType
};
}
解决方法
我想出的最终答案如下
RegistrationRequest.fromJson(Map<String,dynamic> json) => RegistrationRequest(
email: json["email"],password: json["password"],msisdn: json["msisdn"],gender: json["gender"],matchGender: json["matchGender"],userImages: List<UserImage>.from(json["userImages"].map((x) => UserImage.fromJson(x))),);
Map<String,dynamic> toJson() => {
"email": email,"password": password,"msisdn": msisdn,"gender": gender,"matchGender": matchGender,"userImages": List<dynamic>.from(userImages.map((x) => x.toJson())),