【flutter-DIO-JSON】多层嵌套读取

当JSON返回结果是多层嵌套的时候,可以通过逐层解析来提取所需的数据。以下是一个简单的示范例子,展示了如何处理一个3层嵌套的JSON返回结果:

Dart 复制代码
import 'package:dio/dio.dart';

void main() async {
  Dio dio = Dio();

  try {
    Response response = await dio.get('https://jsonplaceholder.typicode.com/todos/1');

    if (response.statusCode == 200) {
      Map<String, dynamic> data = response.data;

      // 提取第一层数据
      int userId = data['userId'];
      int id = data['id'];
      String title = data['title'];

      // 提取第二层数据
      Map<String, dynamic> nestedData = data['nestedData'];
      int nestedId = nestedData['nestedId'];
      String nestedInfo = nestedData['nestedInfo'];

      // 提取第三层数据
      Map<String, dynamic> deeplyNestedData = nestedData['deeplyNestedData'];
      int deeplyNestedId = deeplyNestedData['deeplyNestedId'];
      String deeplyNestedInfo = deeplyNestedData['deeplyNestedInfo'];

      // 打印提取后的数据
      print('User ID: $userId');
      print('ID: $id');
      print('Title: $title');
      print('Nested ID: $nestedId');
      print('Nested Info: $nestedInfo');
      print('Deeply Nested ID: $deeplyNestedId');
      print('Deeply Nested Info: $deeplyNestedInfo');
    } else {
      print('Request failed with status: ${response.statusCode}');
    }
  } catch (e) {
    print('Error: $e');
  }
}

在这个示例中,我们假设返回的JSON数据有3层嵌套结构,我们逐层提取数据并打印出来。可以根据实际情况调整代码以适应您的数据结构。

相关推荐
BG7 小时前
Flutter 简仿Excel表格组件介绍
flutter
zhangmeng11 小时前
FlutterBoost在iOS26真机运行崩溃问题
flutter·app·swift
恋猫de小郭12 小时前
对于普通程序员来说 AI 是什么?AI 究竟用的是什么?
前端·flutter·ai编程
卡尔特斯12 小时前
Flutter A GlobalKey was used multipletimes inside one widget'schild list.The ...
flutter
w_y_fan15 小时前
Flutter 滚动组件总结
前端·flutter
醉过才知酒浓16 小时前
Flutter Getx 的页面传参
flutter
火柴就是我2 天前
flutter 之真手势冲突处理
android·flutter
Speed1232 天前
`mockito` 的核心“打桩”规则
flutter·dart
法的空间2 天前
Flutter JsonToDart 支持 JsonSchema
android·flutter·ios
恋猫de小郭2 天前
Android 将强制应用使用主题图标,你怎么看?
android·前端·flutter