I use FLutter in Android studio, parsing multilevel JSON to a class. Although I have checked many stackoverflow post I can not find a solution for this problem. This is my JSON
String myJson = '
[
{
"sensor":"1234",
"data":
[
{
"value":"40",
"reading_time1":"2021-04-10"
},
{
"value":"38",
"reading_time1":"2021-04-11"
}
]
},
{
"sensor":"1235",
"data":
[
{
"value":"2",
"reading_time1":"2021-04-23"
},
{
"value":"39",
"reading_time1":"2021-04-24"
}
]
}
] '
These are my classes, generated using https://javiercbk.github.io/json_to_dart/ . But the generated code did not work (not null safety) so after reading many post I came up with these:
class AllSensorData {
String sensor="";
List<Sensordata> sensordata = [];
AllSensorData({required this.sensor,required this.sensordata});
AllSensorData.fromJson(Map<String, dynamic> json) {
sensor = json['sensor'];
if (json['data'] != null) {
sensordata = <Sensordata>[];
json['data'].forEach((v) {
sensordata.add(new Sensordata.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sensor'] = this.sensor;
if (this.sensordata != null) {
data['data'] = this.sensordata.map((v) => v.toJson()).toList();
}
return data;
}
}
class Sensordata {
String value;
String reading_time;
Sensordata({
required this.value,
required this.reading_time
});
Sensordata.fromJson(Map<String, dynamic> json) :
value = json['value'],
reading_time = json['reading_time1'];
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['value'] = this.value;
data['reading_time'] = this.reading_time;
return data;
}
}
Now when I run:
var decodedJson = jsonDecode(myJson);
var jsonValue = AllSensorData.fromJson(decodedJson);
The error is:
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
Although I suspect there might be more. Thanks for help.