I get response from backend:
{"measurements": {
"pm10": {
"name": "pm10",
"value": 20.8647,
"unit": "µg/m³"
},
"pm25": {
"name": "pm10",
"value": 20.8647,
"unit": "µg/m³"
},
"o2": {
"name": "pm10",
"value": 20.8647,
"unit": "µg/m³"
}
},
"station": {
"city": "{cityName}",
"name": "{locationName}",
"latitude": "54.353336",
"longitude": "18.635283"
}
}
This is what I got at this moment:
class Pollutions {
Pollutions.fromJsonMap(Map<String, dynamic> map):
measurements = Measurements.fromJsonMap(map["measurements"]),
station = Station.fromJson(map["station"]);
Map<String, Pollution> measurements;
Station station;
Map<String, dynamic> toJson() {
final data = Map<String, dynamic>();
data['measurements'] = measurements == null ? null : measurements.jsonDecode(measurements);
data['station'] = station == null ? null : station.toJson();
return data;
}
}
and in measurements I can get other values and I don't know anything about they names, it could be o2, o3, not only pm10 etc. Can I parse this measurements to map key-value, where key will be pm10, something like that: Map?
How should looks Pollutions.fromJsonMap
and toJson
methods for map?
Following your json object structure, your fetchData method should have the return type of Map<String, Map<String, dynamic>> since it is a Map of a Map. After updating the return type, the missing part of your code is the casting of your decoded response. body to Map<String, Map<String, dynamic>> .
A User.fromJson() constructor, for constructing a new User instance from a map structure. A toJson() method, which converts a User instance into a map.
You can simply do it by using the out-of-the-box decoder from dart:convert
import 'package:http/http.dart' as http;
import 'dart:convert';
final response = await http.get(someEndPoint);
final Map<String, dynamic> data = json.decode(response.body);
Above answer may give the error internal linked hash map is not a subtype of Map.
try this instead:
Map<String, String> map = Map.castFrom(json.decode(jsonString))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With