16

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?

edi233
  • 3,511
  • 13
  • 56
  • 97
  • 4
    Possible duplicate of [The best way to parse a JSON in Dart](https://stackoverflow.com/questions/15866290/the-best-way-to-parse-a-json-in-dart) – Martyns Jun 26 '19 at 10:36

3 Answers3

28

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);
Miguel Ruivo
  • 16,035
  • 7
  • 57
  • 87
10

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))
Dhruv Garg
  • 101
  • 1
  • 2
9
Map<String, dynamic> data = jsonDecode(yourVariable);
Murat Aslan
  • 1,446
  • 9
  • 21