乐闻世界logo
搜索文章和话题

How to Deserialize a list of objects from json in flutter

1个答案

1

In Flutter, deserializing object lists from JSON is a common requirement, especially when handling network requests and responses. We can implement this functionality through several steps. Below, I will describe this process in detail and provide a specific example.

Step 1: Define the Data Model

First, we define a class to represent the JSON data structure. Suppose we have a JSON object list where each object represents a user, including the user's ID, name, and email address.

dart
class User { final int id; final String name; final String email; User({this.id, this.name, this.email}); // Deserialize from JSON factory User.fromJson(Map<String, dynamic> json) { return User( id: json['id'], name: json['name'], email: json['email'], ); } }

Step 2: Write the Parsing Function

Next, we write a function to parse the JSON array and convert it into a list of User objects.

dart
List<User> parseUsers(String responseBody) { final parsed = json.decode(responseBody).cast<Map<String, dynamic>>(); return parsed.map<User>((json) => User.fromJson(json)).toList(); }

Step 3: Use the Parsing Function

Finally, use the above function to deserialize the JSON string into a list of User objects. This is typically done within the callback of a network request.

dart
import 'dart:convert'; import 'package:http/http.dart' as http; Future<List<User>> fetchUsers() async { final response = await http.get('https://api.example.com/users'); if (response.statusCode == 200) { return parseUsers(response.body); } else { throw Exception('Failed to load users'); } }

Example Explanation

In this example, we first create a User class that can be constructed from JSON. Then, we define a parseUsers function that accepts the API response body, uses json.decode to parse the JSON data, and maps it to the User.fromJson factory constructor, ultimately generating a list of User objects.

By doing this, we can easily handle JSON-formatted data from the network and convert it effectively into data models for Flutter applications. This is crucial for developing modern mobile applications with network interactions.

2024年8月8日 00:40 回复

你的答案