json - 如何使用 Flutter 中的默认方法解析复杂的 JSON?

标签 json flutter dart

我有一个 json 字符串{"a":"{\"b\":7}"}。但它不会从默认库中解码。我编写了以下代码:

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

请帮忙解析一下json。

最佳答案

要使用具有深层/多级/递归点表示法的 JSON 对象,您可以使用一个很棒的 Dart 包:g_json 。我发现它 super 简单!

它不使用 Flutter recommended packages for JSON 上生成的代码这些都很复杂。 Dart 和 Flutter 团队必须改进。


我使用一个复杂的 JSON 对象和您的示例,并向您展示如何访问数据(您必须清理您的 JSON 字符串,也许您的示例是从添加额外双引号的地方复制的 "" 括号内)。

现在,看看我的代码:

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']}',
    ));
  }
}

控制台打印下一个结果:

7
String
0.45
"Clouds"

提示

您可以使用Postman从服务获取 API 数据。一个非常有用的工具,相信我!

enter image description here

关于json - 如何使用 Flutter 中的默认方法解析复杂的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69437119/

相关文章:

date - 在 Dart 中获取特定日期的开始时间

dart - Flutter-手机屏幕关闭时如何播放音频

javascript - 创建 jQuery 元素后访问 JSON 数据

python - 通过 REST 将 Swift 数据发送到服务器并执行 Python 代码

flutter - 错误: Undefined name 'context' in flutter

flutter - 将onTap函数传递给Flutter中的另一个小部件

file-io - Dart文件读取到var

python - 如何使用 Python 从 Azure Blob 容器读取文件

javascript - 如何 JSON.parse() 反序列化包含字符串化对象的 JSON.stringify 序列化对象?

flutter - 传入转换为卡住数据类 (fromJson) 的 firestore 文档的 ID