当前位置: 首页 > 知识库问答 >
问题:

例外:类型“String”不是类型“Map

荆修明
2023-03-14

异常:“字符串”类型不是“映射”类型的子类型

{"collection":{"data":"{\"id\": 1, \"name\": \"Marko\", \"picture\": 
\"https://lh3.googleusercontent.com/a-/AAuE7mC1vqaKk_Eylt-fcKgJxuN96yQ7dsd2dBdsdsViK959TKsHQ=s96- 
c\"}","statusCode":202,"version":"1.0"}}

这是上面的json,我只想把它放在用户pojo类中的[data]。

但它抛出了上述异常类型。

class UserCollection {
  final User data;
  final int statusCode;
  final String version;

 UserCollection({this.data, this.statusCode, this.version});

factory UserCollection.fromJson(Map<String, dynamic> json) {
 return UserCollection(
    statusCode: json['statusCode'] as int,
    data: User.fromJson(json['data']) ,
    version: json['version'] as String );
}

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

用户Pojo类

@JsonSerializable()
class User {
final int id;
 final String sub;
 final String home;
 final String work;
 final String name;
 final String mobileNo;
 final String email;
 final String favMechId;
 final String appVersionCode;
 final String picture;
 final String serverTime;
 final String dateCreated;
 final String dateModified;
 final String fcmTokenId;

 User(
  {this.id,
  this.sub,
  this.home,
  this.work,
  this.name,
  this.mobileNo,
  this.email,
  this.favMechId,
  this.appVersionCode,
  this.picture,
  this.serverTime,
  this.dateCreated,
  this.dateModified,
  this.fcmTokenId});



  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String,dynamic> toJson() => _$UserToJson(this); 

为了清晰起见,我推荐了这个中等规模的网站

但在4个多小时的静脉注射中,我不知道发生了什么。如果要更改用户。从()到字符串,然后就可以了。但我需要将[data]从json解析到用户pojo类。

共有1个答案

商泽宇
2023-03-14

试试下面,

factory UserCollection.fromJson(Map<String, dynamic> json) {
 return UserCollection(
    statusCode: json['statusCode'] as int,
    data: User.fromJson(json.decode(json['data'])),
    version: json['version'] as String );
}

数据中的更改:用户。fromJson(json.decode(json['data']),

 类似资料: