Flutter如何查看和解析JSON数据
在Flutter开发中,如何查看和解析从API获取的JSON数据?具体有哪些方法和步骤?
2 回复
在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)
- 添加依赖到
pubspec.yaml:
dependencies:
json_annotation: ^4.8.1
dev_dependencies:
build_runner: ^2.4.4
json_serializable: ^6.7.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);
}
- 生成代码:
flutter pub run build_runner build
- 使用模型类解析:
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项目使用。


