Home > OS >  How to parse json file contain list of map to dart file in flutter
How to parse json file contain list of map to dart file in flutter

Time:09-30

I used this code but i found this error DioError (DioError [DioErrorType.other]: type 'List' is not a subtype of type 'Map<String, dynamic>?' in type cast


This is json file i won't to parse


//-- Get Note Response

@JsonSerializable()
class NoteDataResponse {
  @JsonKey(name: "text")
  String? text;
  @JsonKey(name: "placeDateTime")
  String? placeDateTime;
  @JsonKey(name: "userId")
  String? userId;
  @JsonKey(name: "id")
  String? id;
  NoteDataResponse(this.text, this.placeDateTime, this.userId, this.id);
  factory NoteDataResponse.fromJson(Map<String, dynamic> json) =>
      _$NoteDataResponseFromJson(json);

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

@JsonSerializable()
class NoteResponse extends BaseResponse {
  List<NoteDataResponse>? noteDataResponse;
  NoteResponse(this.noteDataResponse);
  factory NoteResponse.fromJson(Map<String, dynamic> json) =>
      _$NoteResponseFromJson(json);

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

CodePudding user response:

use quicktype to parse json files easly

CodePudding user response:

your API response is a list not a Map. here what makes error: fromJson required args Map<String,dynamic>

NoteResponse.fromJson(Map<String, dynamic> json)

use this on your function when getting the response api

final listNote = (jsonDecode(response.body) as List).map((e) => 
                     NoteDataResponse .fromJson(e)).toList();

your class NoteResponse will fine if the response you got is a list of Map, which is has key and value, like below:

[
 "key1": { "text"; "dasdad", .....},
 "key2": { "text"; "dasdad", .....},
 ....
]

CodePudding user response:

Your JSON response starts with the list. So you need to Iterate it.

final responseList = (_response as Iterable)
            .map((e) =>  NoteDataResponse.fromJson(e as Map<String,dynamic>))
            .toList();
  • Related