在flutter中,List的json解码< String>不起作用

kmb7vmvb  于 2023-03-19  发布在  Flutter
关注(0)|答案(3)|浏览(145)

我有这样的课:

class ErrorMessage {
  int          statusCode;
  List<String> message;
  String       error;
  ErrorMessage(this.statusCode, this.message, this.error);

  factory ErrorMessage.fromJson(Map<String, dynamic> json) => ErrorMessage(
    json['statusCode'],
    json['message'],
    json['error']
  );
}

当我用这个数据调用fromJson时:

res.body : {"statusCode":400,"message":["Please enter a name."],"error":"Bad Request"}

我得到这个错误:type 'List<dynamic>' is not a subtype of type 'List<String>'
message好像没有转换成List<String>,怎么转换?

tzcvj98z

tzcvj98z1#

在如下循环中使用类型转换将List<dynamic>转换为List<String>

class ErrorMessage {
  /// {@macro error_message}
  const ErrorMessage({ 
    required this.statusCode,
    required this.message,
    required this.error,
  });

    /// Creates a ErrorMessage from Json map
  factory ErrorMessage.fromJson(Map<String, dynamic> json) =>ErrorMessage(
      statusCode: json['statusCode'] as int,
      message:
          (json['message'] as List<dynamic>).map((e) => e as String).toList(),
      error: json['error'] as String,
    );

  final int statusCode;
  final List<String> message;
  final String error;
}
ddarikpa

ddarikpa2#

尝试以下型号

class Response {
  Response({
      this.statusCode,
      this.message,
      this.error,
  });

  int? statusCode;
  List<String>? message;
  String? error;

  factory Response.fromJson(Map<String, dynamic> json) => Response(
      statusCode: json["statusCode"],
      message: json["message"] == null ? [] : List<String>.from(json["message"]!.map((x) => x)),
      error: json["error"],
  );
  
}
jdgnovmf

jdgnovmf3#

您需要分别对StringList执行map操作,如下所示:
变更

factory ErrorMessage.fromJson(Map<String, dynamic> json) => ErrorMessage(
    json['statusCode'],
    json['message'],
    json['error']
  );

factory ErrorMessage.fromJson(Map<String, dynamic> json) =>ErrorMessage(
      statusCode: json['statusCode'] as int,
      message:(json['message']).map((e) => e as String).toList(), //👈 Emphasis on this
      error: json['error'] as String,
    );

相关问题