json 异常:类型'String'不是类型'Map〈String,dynamic>的子类型

3phpmpom  于 2023-03-24  发布在  其他
关注(0)|答案(2)|浏览(123)

例外情况:类型“String”不是类型“Map〈String,dynamic〉”的子类型

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

这是上面的json,我想把它放在User 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;
 }
}

User Pojo class

@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);

为了清楚起见,我引用了这个中等站点,medium flutter json
但在静脉超过4小时,我不能什么是错的.如果改变用户.从()到字符串,那么它的好.但我需要解析[数据]从json到用户pojo类.

ilmyapht

ilmyapht1#

试试下面

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 );
}

data: User.fromJson(json.decode(json['data'])),中的变化

yqlxgs2m

yqlxgs2m2#

factory UserCollection.fromJson(Map<String, dynamic> json) => UserCollection(
  statusCode : json["statusCode"],
  version: json["version"],
  user: User.fromJson(json["user"])

);

相关问题