Flutter如何查看和解析JSON数据

在Flutter开发中,如何查看和解析从API获取的JSON数据?具体有哪些方法和步骤?

2 回复

在Flutter中,使用dart:convert库的json.decode()解析JSON字符串为Map或List。使用json.encode()将对象转换为JSON字符串。对于复杂数据,可使用json_annotation库自动生成序列化代码。

更多关于Flutter如何查看和解析JSON数据的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中查看和解析JSON数据可以通过以下步骤实现:

1. 查看JSON数据

  • 使用print()debugPrint()输出原始JSON字符串。
  • 使用Flutter DevTools的调试工具查看网络请求返回的JSON数据。

2. 解析JSON数据

手动解析(适用于简单JSON)

使用dart:convert库的json.decode()

import 'dart:convert';

void parseJson() {
  String jsonString = '{"name": "John", "age": 30}';
  Map<String, dynamic> data = json.decode(jsonString);
  print(data['name']); // 输出: John
}

自动生成模型类(推荐用于复杂JSON)

  1. 添加依赖到pubspec.yaml
dependencies:
  json_annotation: ^4.8.1

dev_dependencies:
  build_runner: ^2.4.4
  json_serializable: ^6.7.1
  1. 创建模型类(例如user.dart):
import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  final String name;
  final int age;

  User({required this.name, required this.age});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
  1. 生成代码:
flutter pub run build_runner build
  1. 使用模型类解析:
void parseWithModel() {
  String jsonString = '{"name": "John", "age": 30}';
  User user = User.fromJson(json.decode(jsonString));
  print(user.name); // 输出: John
}

3. 处理网络JSON数据

结合http包:

import 'package:http/http.dart' as http;

Future<User> fetchUser() async {
  final response = await http.get(Uri.parse('https://api.example.com/user'));
  if (response.statusCode == 200) {
    return User.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load data');
  }
}

注意事项

  • 使用try-catch处理解析异常
  • 对于嵌套JSON建议使用模型类
  • 确保JSON格式正确

这种方法兼顾了开发效率和类型安全,适合Flutter项目使用。

回到顶部