flutter的JSON的序列化和反序列化
时间: 2024-03-02 22:44:53 浏览: 251
Flutter中的JSON序列化和反序列化可以使用内置的dart:convert库中的jsonDecode()和jsonEncode()方法来实现。具体方法如下:
1. JSON反序列化
使用jsonDecode()方法将JSON字符串转换为Dart对象。例如:
```dart
import 'dart:convert';
String jsonString = '{"name": "John Smith", "email": "john@example.com"}';
Map<String, dynamic> user = jsonDecode(jsonString);
print('Name: ${user['name']}, Email: ${user['email']}');
```
输出结果为:
```
Name: John Smith, Email: john@example.com
```
2. JSON序列化
使用jsonEncode()方法将Dart对象转换为JSON字符串。例如:
```dart
import 'dart:convert';
Map<String, dynamic> user = {'name': 'John Smith', 'email': 'john@example.com'};
String jsonString = jsonEncode(user);
print(jsonString);
```
输出结果为:
```
{"name":"John Smith","email":"john@example.com"}
```
阅读全文
相关推荐


















