一、在線json轉(zhuǎn)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轉(zhuǎn)換成model
小工具
3.在根目錄運(yùn)行
-
flutter packages pub run build_runner buildmodel類更改時(shí)都需要手動(dòng)運(yùn)行構(gòu)建 -
flutter packages pub run build_runner watchmodel類更改時(shí)不需要手動(dòng)運(yùn)行構(gòu)建 -
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);
