如何在没有关键的情况下解析JSON
我想解析一个JSON.但是此JSON没有键值.只是价值.
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'.
我试图解析它们在json中所占的位置(例如:json [0]....)但是我对此不确定.
I tried to parse in the positions they occupy in the json (eg.: json [0] ....) But I'm not sure about this.
预先感谢
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"]]
班级列表:
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)));
}
}
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]);
}
}
json.decode()
返回dynamic
,因为json的每个元素都可以是对象(成为Dart Map
)或数组(成为Dart
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]);
}