How can I parse a List inside a List in Flutter?
719
Nothing special here, since the inner list has String type, you should use
List<List<String>> capitulos
and you should make necessary changes for fromJson and toJson as well.
Author by
AnthonyAquino
Updated on December 17, 2022Comments
-
AnthonyAquino over 1 year
I'm having problem parsin this json because I can parse "indice" but I can parse "capitulos". I get the error: Exception has occurred. _TypeError (type 'String' is not a subtype of type 'Map') How can I parse a list inside a list, please? I read a great article by Pooja Bhaumik but id does not covert this example.
[ { "id": "1", "title": "title", "origem": "origin", "tipo": "type", "indice": [ { "id": 1, "title": "title 1" }, { "id": 2, "title": "title 2" }, ], "capitulos": [ [ "chapter 1 text 1", "chapter 1 text 2", "chapter 1 text 3" ], [ "chapter 2 text 1", "chapter 2 text 2", "chapter 2 text 3" ], ] } ]
My model:
class DocumentosList { final List<Documento> documentos; DocumentosList({ this.documentos, }); factory DocumentosList.fromJson(List<dynamic> parsedJson) { List<Documento> documentos = new List<Documento>(); documentos = parsedJson.map((i) => Documento.fromJson(i)).toList(); return new DocumentosList(documentos: documentos); } } class Documento { String id; String title; String origem; String tipo; List<IndiceItem> indice; List<Capitulos> capitulos; Documento({ this.id, this.title, this.origem, this.tipo, this.indice, this.capitulos, }); factory Documento.fromJson(Map<String, dynamic> parsedJson) { var list = parsedJson['indice'] as List; List<IndiceItem> indice = list.map((i) => IndiceItem.fromJson(i)).toList(); var listCapitulos = parsedJson['capitulos']; List<Capitulos> capitulos = listCapitulos.map((i) => Capitulos.fromJson(i)).toList(); return new Documento( id: parsedJson['id'], title: parsedJson['title'], origem: parsedJson['origem'], indice: indice, capitulos: capitulos, ); } } class IndiceItem { String id; String title; IndiceItem({ this.id, this.title, }); factory IndiceItem.fromJson(Map<String, dynamic> parsedJson) { return IndiceItem( id: parsedJson['id'].toString(), title: parsedJson['title'], ); } } class Capitulos { final List<Capitulo> capitulos; Capitulos({this.capitulos}); factory Capitulos.fromJson(List<dynamic> parsedJson) { List<Capitulo> capitulos = new List<Capitulo>(); capitulos = parsedJson.map((i) => Capitulo.fromJson(i)).toList(); return new Capitulos(capitulos: capitulos); } } class Capitulo { final List<String> paragrafos; Capitulo({this.paragrafos}); factory Capitulo.fromJson(Map<String, dynamic> parsedJson) { var paragrafosFromJson = parsedJson['paragrafos']; List<String> paragrafosList = paragrafosFromJson.cast<String>(); return new Capitulo( paragrafos: paragrafosList, ); } }
-
Payam Asefi about 4 yearsthe error occures in this line ?
List<String> paragrafosList = paragrafosFromJson.cast<String>();
?
-