Flutter如何处理JSON数据
在Flutter中处理JSON数据时,如何将JSON字符串转换为Dart对象?是否有推荐的方法或库来实现高效解析?另外,如何处理嵌套复杂的JSON结构,以及如何将Dart对象转换回JSON字符串?希望能提供一些实际代码示例来说明这些操作。
2 回复
Flutter使用dart:convert库处理JSON。
- 手动解析:通过
json.decode()将JSON字符串转为Map,再手动提取数据。 - 自动解析:使用
json_annotation和json_serializable库自动生成模型类解析代码,更高效安全。
更多关于Flutter如何处理JSON数据的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中处理JSON数据主要有两种方式:手动序列化和自动序列化。
1. 手动序列化(使用 dart:convert)
import 'dart:convert';
// JSON字符串
String jsonString = '{"name": "张三", "age": 25, "email": "zhangsan@example.com"}';
// 解析JSON
Map<String, dynamic> user = jsonDecode(jsonString);
print(user['name']); // 输出:张三
// 生成JSON
Map<String, dynamic> userMap = {
'name': '李四',
'age': 30,
'email': 'lisi@example.com'
};
String jsonOutput = jsonEncode(userMap);
2. 自动序列化(推荐)
步骤1:添加依赖
dependencies:
json_annotation: ^4.8.1
dev_dependencies:
build_runner: ^2.4.4
json_serializable: ^6.7.1
步骤2:创建模型类
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
final String name;
final int age;
final String email;
User({required this.name, required this.age, required this.email});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
步骤3:生成代码 在终端运行:
flutter pub run build_runner build
步骤4:使用模型类
// 解析JSON
Map<String, dynamic> userMap = jsonDecode(jsonString);
User user = User.fromJson(userMap);
// 生成JSON
String jsonString = jsonEncode(user.toJson());
3. 处理复杂JSON结构
对于嵌套JSON:
@JsonSerializable()
class Address {
final String city;
final String street;
Address({required this.city, required this.street});
factory Address.fromJson(Map<String, dynamic> json) => _$AddressFromJson(json);
Map<String, dynamic> toJson() => _$AddressToJson(this);
}
@JsonSerializable()
class User {
final String name;
final Address address;
User({required this.name, required this.address});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
4. 网络请求中的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(jsonDecode(response.body));
} else {
throw Exception('Failed to load user');
}
}
推荐使用自动序列化,因为它提供类型安全、减少错误,并且易于维护。对于简单项目或快速原型,手动序列化也是可行的选择。

