Flutter Notes: Serialization and Deserialization

Flutter notes
Serialization and deserialization

Author : Li Juncai (jcLee95) : https://blog.csdn.net/qq_28550263
Email: [email protected]
Article address : https://blog.csdn.net/qq_28550263/article/details/133340592



1 Overview

Serialization is a process of converting complex data structures (such as objects, arrays, dictionaries, etc.) into a linear format or byte stream to facilitate data storage, transmission, and sharing. Through serialization, data is converted into a persistent, transportable, platform-independent format, which allows the data to be interacted and interoperated between different applications, programming languages, and systems. Serialization is commonly used for data persistence (saving application state to disk), data transmission (passing data in network communications), data storage (stored objects in a database or cache), remote procedure calls (in distributed systems calling remote methods) and message passing (delivering messages in a message queue or event bus). Different serialization formats (such as JSON, XML, binary serialization, etc.) can be selected according to needs to achieve data readability, efficiency, and compatibility.

In actual development, the main uses of serialization include:

use describe
Data persistence Save an application's state, configuration, or user data in a serialized manner to disk or other storage media so that it can be reloaded when the application is restarted. This is useful for saving user preferences, game progress, application state, etc.
data transmission In network communication, data usually needs to be passed between the client and the server. Serialization can convert complex data structures (such as objects, arrays, dictionaries, etc.) into transportable formats, such as JSON or XML, to facilitate cross-platform communication. This is important for data exchange between web applications, mobile applications, and backend services.
Cross-platform compatibility When sharing data across multiple programming languages ​​and platforms, serialization enables data to remain consistent across different environments. For example, you can serialize data to JSON in a service written in Python, and then deserialize the data in a front-end application written in JavaScript.
Remote Procedure Call (RPC) Some distributed systems use serialization to call methods on remote servers and pass parameters. Serialization allows data and instructions to be passed between clients and servers in order to perform remote operations.
Data storage and retrieval When using a database or cache to store data, objects are serialized into formatted data and then stored for later retrieval and use. In this case, serialization is typically used to convert objects into table rows in a relational database or to store objects in a NoSQL database.
messaging In a message queuing system or event bus, serialization is used to deliver messages or events to different application components or services.

Serialization allows data to flow and be shared between different environments and applications, enabling data persistence, cross-platform interoperability, and distributed communication. Different programming languages ​​and platforms usually support different serialization formats (such as JSON, XML, Protobuf, MessagePack, etc.), and developers need to choose the appropriate serialization method and format based on specific needs and scenarios.

2. JSON serialization and deserialization

2.1 Serialization of objects to JSON

To serialize and deserialize JSON in Dart, you first need to import Dart's dart:convertlibrary, which provides tools for processing JSON data.
To serialize Dart objects into JSON format, you can use json.encode()the function:

import 'dart:convert';

Map<String, dynamic> user = {
    
    
  'name': 'Jack',
  'age': 28,
};

String jsonUser = json.encode(user);
print(jsonUser);

2.2 Deserialization of JSON to objects

To deserialize JSON data into Dart objects, you can use json.decode()the function:

import 'dart:convert';

String jsonUser = '{"name": "Jack", "age": 28}';
Map<String, dynamic> user = json.decode(jsonUser);
print(user['name']); // 输出 "Jack"

3. Serialization and deserialization of custom objects

3.1 Implement custom serialization and deserialization methods

Suppose we have a custom Dart class representing user information. In order to implement the serialization and deserialization of custom objects, we can Useradd toJson()the and fromJson()methods in the class:

import 'dart:convert';

class User {
    
    
  String name;
  int age;

  User(this.name, this.age);

  // 序列化为 JSON
  Map<String, dynamic> toJson() {
    
    
    return {
    
    
      'name': name,
      'age': age,
    };
  }

  // 从 JSON 反序列化
  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'];
}

3.2 Using custom serialization and deserialization

Now we can convert custom objects to JSON format and deserialize from JSON to objects:

import 'dart:convert';

User user = User('Jack', 28);

// 对象到 JSON
String jsonUser = json.encode(user.toJson());
print(jsonUser);

// JSON 到对象
Map<String, dynamic> userMap = json.decode(jsonUser);
User newUser = User.fromJson(userMap);
print(newUser.name); // 输出 "Jack"

By implementing toJson()the and fromJson()methods, we can customize the serialization and deserialization process of objects to suit specific data structures and needs.

4. Serialization and deserialization of nested objects

If the object contains nested objects, you can recursively call the serialization and deserialization methods in the toJson()and methods to handle the nested objects.fromJson()

import 'dart:convert';

class Address {
    
    
  String street;
  String city;

  Address(this.street, this.city);

  Map<String, dynamic> toJson() {
    
    
    return {
    
    
      'street': street,
      'city': city,
    };
  }
  /// 从 JSON 格式的 Map 反序列化为 Address 对象
  Address.fromJson(Map<String, dynamic> json)
      : street = json['street'],
        city = json['city'];
}

class User {
    
    
  String name;
  int age;
  Address address;

  User(this.name, this.age, this.address);
  
  /// 将 User 对象转换为 JSON 格式的 Map
  Map<String, dynamic> toJson() {
    
    
    return {
    
    
      'name': name,
      'age': age,
      'address': address.toJson(),
    };
  }
  
  /// 从 JSON 格式的 Map 反序列化为 User 对象
  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'],
        address = Address.fromJson(json['address']);
}

Next, we demonstrate how to use Addressthe and Userclasses for serialization and deserialization:

First, let's create an Addressobject and an Userobject and convert them to JSON format:

void main() {
    
    
  // 创建一个 Address 对象
  Address userAddress = Address('123 Main St', 'Cityville');

  // 创建一个 User 对象,包括姓名、年龄和地址信息
  User user = User('John Doe', 30, userAddress);

  // 将 User 对象转换为 JSON 格式
  Map<String, dynamic> userJson = user.toJson();
  print(userJson);
}

In the above code, we first create an Addressobject and an Userobject. Then, we use toJson()the method to Userconvert the object into a JSON-formatted Mapobject and print it out. This will produce the following JSON data:

{
    
    
  "name": "John Doe",
  "age": 30,
  "address": {
    
    
    "street": "123 Main St",
    "city": "Cityville"
  }
}

Next, we'll show how to deserialize the above JSON data into Useran object:

void main() {
    
    
  // JSON 格式的用户数据
  Map<String, dynamic> jsonUserData = {
    
    
    "name": "Alice Smith",
    "age": 25,
    "address": {
    
    
      "street": "456 Elm St",
      "city": "Townsville"
    }
  };

  // 从 JSON 格式的数据反序列化为 User 对象
  User newUser = User.fromJson(jsonUserData);

  // 打印新创建的 User 对象的属性
  print('Name: ${
      
      newUser.name}');
  print('Age: ${
      
      newUser.age}');
  print('Street: ${
      
      newUser.address.street}');
  print('City: ${
      
      newUser.address.city}');
}

In the above code, we first define a user data in JSON format. We then used User.fromJson()the method to deserialize the JSON data into Useran object and output Userthe properties of the newly created object.

These two examples demonstrate how to use the Addressand Userclasses for serialization and deserialization of objects to facilitate data storage and transmission. Serialization converts objects into JSON data, while deserialization restores JSON data to objects, enabling efficient interaction and sharing of data between different application components or systems.

Guess you like

Origin blog.csdn.net/qq_28550263/article/details/133340592