dart 在flutter中解析JSON到Map

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

我从后端得到响应:

{"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"
    }
    }

这是我在这一刻得到的:

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

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

c0vxltue

c0vxltue1#

您可以通过使用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);
ni65a41a

ni65a41a2#

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

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

hyrbngr73#

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

btxsgosb4#

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

相关问题