Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON to Map in flutter

Tags:

flutter

dart

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?

like image 909
edi233 Avatar asked Jun 26 '19 10:06

edi233


People also ask

How do I parse nested JSON in flutter?

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>> .

What does fromJson do in flutter?

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.


2 Answers

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);
like image 185
Miguel Ruivo Avatar answered Sep 18 '22 19:09

Miguel Ruivo


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))
like image 32
Dhruv Garg Avatar answered Sep 18 '22 19:09

Dhruv Garg