在Flutter中访问REST API的JSON数组的复杂内部元素,通常涉及以下步骤:
http
或dio
包)向服务器发送请求并接收响应。假设我们有一个JSON响应如下:
{
"users": [
{
"id": 1,
"name": "John Doe",
"address": {
"street": "123 Main St",
"city": "Anytown"
}
},
{
"id": 2,
"name": "Jane Smith",
"address": {
"street": "456 Elm St",
"city": "Othertown"
}
}
]
}
我们可以定义以下Dart类来表示这个结构:
class Address {
final String street;
final String city;
Address({required this.street, required this.city});
factory Address.fromJson(Map<String, dynamic> json) {
return Address(
street: json['street'],
city: json['city'],
);
}
}
class User {
final int id;
final String name;
final Address address;
User({required this.id, required this.name, required this.address});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
address: Address.fromJson(json['address']),
);
}
}
class ApiResponse {
final List<User> users;
ApiResponse({required this.users});
factory ApiResponse.fromJson(Map<String, dynamic> json) {
return ApiResponse(
users: List<User>.from(json['users'].map((user) => User.fromJson(user))),
);
}
}
然后,我们可以使用http
包来发送请求并解析响应:
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> fetchUsers() async {
final response = await http.get(Uri.parse('https://api.example.com/users'));
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
final apiResponse = ApiResponse.fromJson(jsonResponse);
for (var user in apiResponse.users) {
print('User ID: ${user.id}, Name: ${user.name}, City: ${user.address.city}');
}
} else {
print('Failed to load users');
}
}
jsonDecode
正确解析。async
和await
正确处理异步操作。通过以上步骤,你可以轻松在Flutter中访问REST API的复杂JSON数组元素。
领取专属 10元无门槛券
手把手带您无忧上云