3

I want parse a JSON. But this JSON not have key-value. Is only value.

I tried creating the class but dont work. The error is type 'List' is not a subtype of type 'Map'.

I tried to parse in the positions they occupy in the json (eg.: json [0] ....) But I'm not sure about this.

Thanks in advance

Json:

[["P170","P171","L-18"],["P171","L806","L-18"],["L806","L807","L-18"],["L807","L120","L-18"],["L120","L121","L-18"],["L121","L122","L-18"]]

Class list:

import 'NodoPOJO.dart';
class NodoCollection{
  final List<NodoPOJO> list;

  NodoCollection(this.list);

  factory NodoCollection.fromJson(Map<String, dynamic> json) {
    return NodoCollection(
        List.from(json[0]).map((object) =>NodoPOJO.fromJson(object)));
  }


}

class POJO:

class NodoPOJO{
  final String extremo1;
  final String extremo2;
  final String linea;

  NodoPOJO(this.extremo1, this.extremo2, this.linea);


  factory NodoPOJO.fromJson(Map<String, dynamic> json) {
    return NodoPOJO(json[0], json[1],json[2]);
  }

}
3
  • 1
    try deserializing to List<List<String>> Commented Jul 6, 2019 at 20:09
  • Where do I put that exactly? Commented Jul 6, 2019 at 21:16
  • 1
    first thing dude its a List type and not a JSON Object Commented Jul 7, 2019 at 2:39

1 Answer 1

11

json.decode() returns a dynamic because each element of json could be an object (becomes a Dart Map) or array (becomes a Dart List). The json decode doesn't know what it is going to return until it starts decoding.

Rewrite your two classes as follows:

class NodoCollection {
  final List<NodoPOJO> list;

  NodoCollection(this.list);

  factory NodoCollection.fromJson(List<dynamic> json) =>
      NodoCollection(json.map((e) => NodoPOJO.fromJson(e)).toList());
}

class NodoPOJO {
  final String extremo1;
  final String extremo2;
  final String linea;

  NodoPOJO(this.extremo1, this.extremo2, this.linea);

  factory NodoPOJO.fromJson(List<dynamic> json) =>
      NodoPOJO(json[0], json[1], json[2]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much your solution was useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.