一、在线json转dart
https://javiercbk.github.io/json_to_dart/
二、使用 json_serializable解析
- 在
pubspec.yaml
中引入框架
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.3
json_annotation: ^3.0.1
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.7.2
json_serializable: ^3.2.5
- 使用https://caijinglong.github.io/json2dart/index_ch.html转换成model
小工具
3.在根目录运行
-
flutter packages pub run build_runner build
model类更改时都需要手动运行构建 -
flutter packages pub run build_runner watch
model类更改时不需要手动运行构建 -
flutter packages pub run build_runner build --delete-conflicting-outputs
删除user.g.dart
4.使用
import 'dart:convert';
Map userMap = JSON.decode(json);
var user = new User.fromJson(userMap);
String json = JSON.encode(user);