dart 在flutter中解析JSON到Map

jdg4fx2g  于 2023-10-13  发布在  Flutter
关注(0)|答案(4)|浏览(148)

我从后端得到响应:

  1. {"measurements": {
  2. "pm10": {
  3. "name": "pm10",
  4. "value": 20.8647,
  5. "unit": "µg/m³"
  6. },
  7. "pm25": {
  8. "name": "pm10",
  9. "value": 20.8647,
  10. "unit": "µg/m³"
  11. },
  12. "o2": {
  13. "name": "pm10",
  14. "value": 20.8647,
  15. "unit": "µg/m³"
  16. }
  17. },
  18. "station": {
  19. "city": "{cityName}",
  20. "name": "{locationName}",
  21. "latitude": "54.353336",
  22. "longitude": "18.635283"
  23. }
  24. }

这是我在这一刻得到的:

  1. class Pollutions {
  2. Pollutions.fromJsonMap(Map<String, dynamic> map):
  3. measurements = Measurements.fromJsonMap(map["measurements"]),
  4. station = Station.fromJson(map["station"]);
  5. Map<String, Pollution> measurements;
  6. Station station;
  7. Map<String, dynamic> toJson() {
  8. final data = Map<String, dynamic>();
  9. data['measurements'] = measurements == null ? null : measurements.jsonDecode(measurements);
  10. data['station'] = station == null ? null : station.toJson();
  11. return data;
  12. }
  13. }

在测量中,我可以得到其他值,我不知道它们的名字,它可能是o2,o3,而不仅仅是pm10等。我可以解析这个度量值来Map键值吗,其中key将是pm10,类似这样:Map?应该如何看待Pollutions.fromJsonMaptoJson方法的Map?

c0vxltue

c0vxltue1#

您可以通过使用dart:convert中的 * 开箱即用 * 解码器来简单地实现这一点

  1. import 'package:http/http.dart' as http;
  2. import 'dart:convert';
  3. final response = await http.get(someEndPoint);
  4. final Map<String, dynamic> data = json.decode(response.body);
ni65a41a

ni65a41a2#

以上答案可能会给予错误内部链接的哈希map不是Map的子类型。
试试这个:

  1. Map<String, String> map = Map.castFrom(json.decode(jsonString))
hyrbngr7

hyrbngr73#

  1. Map<String, dynamic> data = jsonDecode(yourVariable);
btxsgosb

btxsgosb4#

  1. var jsonResponse = convert.jsonDecode(response.body);

相关问题