rjose
rjose

Reputation: 33

How to parse JSON without key in flutter

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

}

Upvotes: 3

Views: 6157

Answers (1)

Richard Heap
Richard Heap

Reputation: 51751

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

Upvotes: 11

Related Questions