How to parse complex JSON using default methods in Flutter?

Issue

I have a json String {"a":"{\"b\":7}"}. But it does not get decoded from the default library. I have written the following code:

import 'dart:convert';
void main() {
  String a 
        '{"a":"{\"b\":7}"}';
   print(json.decode(a));
}

Please help to parse the json.

Solution

To work with JSON objects that have deep/multiple levels/recursive dot notation, then you can use a fantastic Dart package: g_json. I find it super easy and simple!

It doesn’t use generated code as on Flutter recommended packages for JSON and these are complicated. Dart & Flutter teams have to improve.


I use a complex JSON object and your example and I show you how I access the data (you have to clean your JSON string, maybe your example is copied from a place that add extra double quotes " " on brackets).

Now, look at my code:

import 'dart:convert';
import 'package:g_json/g_json.dart';

void main() {
  String jsonSimple  '{"a":"1"}';

  // Get value from only one level JSON object.
  final Map<String, dynamic> resultSimple  json.decode(jsonSimple);
  print(resultSimple);

  // Deep JSON object
  // This is a real JSON data from api.openweathermap.org/data/2.5/weather?qBarcelona&appid<your_api_key>. You can try it on your browser, put it on the url and press `ENTER`.
  String jsonWeather  jsonEncode({
    "coord": {"lon": 2.159, "lat": 41.3888},
    "weather": [
      {
        "id": 803,
        "main": "Clouds",
        "description": "broken clouds",
        "icon": "04d"
      }
    ],
    "base": "stations",
    "main": {
      "temp": 291.21,
      "feels_like": 291.11,
      "temp_min": 289.53,
      "temp_max": 293.62,
      "pressure": 1016,
      "humidity": 78
    },
    "visibility": 10000,
    "wind": {"speed": 0.45, "deg": 212, "gust": 1.79},
    "clouds": {"all": 75},
    "dt": 1633360018,
    "sys": {
      "type": 2,
      "id": 18549,
      "country": "ES",
      "sunrise": 1633326668,
      "sunset": 1633368526
    },
    "timezone": 7200,
    "id": 3128760,
    "name": "Barcelona",
    "cod": 200
  });
  print(jsonWeather);

  /// It prints: `String`
  print(jsonWeather.runtimeType);

  var resultDeep  JSON.parse(jsonWeather);
  print(resultDeep['wind']['speed'].rawString());
  print(resultDeep['weather'][0]['main'].rawString());

  // Your example with some cleaning.
  String jsonExample  jsonEncode({
    "a": {"b": 7}
  });
  resultDeep  JSON.parse(jsonExample);
  print(resultDeep['a']['b'].rawString());
}

The console prints the next outcome:

String
0.45
"Clouds"
7

Tips

You can use Postman to fetch API data from services. A very useful tool, trust me!

enter image description here

Answered By – Guillem Puche

Leave a Comment