官方Json解析 https://flutter.dev/docs/development/data-and-backend/json
主要过程如下:
1、添加依赖:
dependencies:
json_annotation: ^3.1.1
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.10.11
json_serializable: ^3.5.1
如官方Demo,假如要生成一个user Bean
import 'package:json_annotation/json_annotation.dart';
/// This allows the `User` class to access private members in
/// the generated file. The value for this is *.g.dart, where
/// the star denotes the source file name.
part 'user.g.dart';
/// An annotation for the code generator to know that this class needs the
/// JSON serialization logic to be generated.
@JsonSerializable()
class User {
User(this.name, this.email);
String name;
String email;
/// A necessary factory constructor for creating a new User instance
/// from a map. Pass the map to the generated `_$UserFromJson()` constructor.
/// The constructor is named after the source class, in this case, User.
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
/// `toJson` is the convention for a class to declare support for serialization
/// to JSON. The implementation simply calls the private, generated
/// helper method `_$UserToJson`.
Map<String, dynamic> toJson() => _$UserToJson(this);
}
fromJson 和toJson 都是Bean 文件需要固定有的,JsonSerializable标记该文件需要序列化
part 'user.g.dart'; 是后期编译自动生成的文件
User(this.name, this.email); 构造方法可以不传参数,但必须有构造方法。
cd 到根目录,执行 flutter packages pub run build_runner build 命令,就会生成 user.g.dart文件,如下
json_serializable dart 库地址:https://pub.dev/packages/json_serializable/install
第三方插件 Json解析
在Settings的Plugins下载FlutterJsonBeanFactory
安装好插件之间通过创建新文件
如上就生成了user_entity文件了,user_entity文件名称是插件自动生成的。同时会生成一个generated文件目标里面会有对应的helper和json_convert_content.
动态解析:
大多数服务端返回的数据Json如下
{
"code":0,
"message":"",
"data":{
}
}
而data 可能是JsonObject,也可能是JsonArray,插件是做不了的,可以先以Object形式解析,然后再手动把data改成dynamic,在手动修改一下 helper即可。
class DataEntity with JsonConvert<DataEntity> {
int code;
String msg;
dynamic data;
}