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

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

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 data = response.data;

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

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

      // 提取第三层数据
      Map 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层嵌套结构,我们逐层提取数据并打印出来。可以根据实际情况调整代码以适应您的数据结构。

你可能感兴趣的:(flutter,开发语言)