Shubham Baranwal
Shubham Baranwal

Reputation: 29

How to parse complex JSON using default methods in Flutter?

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.

Upvotes: 2

Views: 211

Answers (2)

Guillem Puche
Guillem Puche

Reputation: 1414

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

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

  // Deep JSON object
  // This is a real JSON data from api.openweathermap.org/data/2.5/weather?q=Barcelona&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);
  resultDeep = JSON.parse(jsonWeather);
  print(resultDeep['wind']['speed'].rawString());
  print(resultDeep['weather'][0]['main'].rawString());

  // Extract data for each item of the array.
  final List<dynamic> listJsonWeather = resultDeep['weather'].value;
  List<WeatherEntity> listWeathers = [];
  for (dynamic jsonWeather in listJsonWeather) {
    listWeathers.add(WeatherEntity(
      id: jsonWeather['id'].toString(),
      title: jsonWeather['main'] as String,
      overview: jsonWeather['description'] as String,
      image: '<url>/${jsonWeather['icon']}',
    ));
  }
}

The console prints the next outcome:

7
String
0.45
"Clouds"

Tips

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

enter image description here

Upvotes: 2

KuKu
KuKu

Reputation: 7502

I implemented with your json string.

enter image description here

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

Upvotes: 0

Related Questions