时间:2022-04-27 10:27:12 | 栏目:Android代码 | 点击:次
class CategoryMo { String name; int count; CategoryMo({this.name, this.count}); //将map转成mo CategoryMo.fromJson(Map<String, dynamic> json) { name = json['name']; count = json['count']; } //将mo转成map,可缺省 Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['name'] = this.name; data['count'] = this.count; return data; } }
person.json
{ "name": "Jack", "age": 20 }
model转换与使用
var personMap = { "name": "Jack", "age": 20 }; Person person = Person.fromJson(personMap); print('name:${person.name}'); print('age:${person.age}');
安装插件
dependencies: ... dio: ^3.0.10 json_annotation: ^3.1.0 dev_dependencies: ... json_serializable: ^3.5.0 build_runner: ^1.0.0
配置实体类
{ "code": 0, "method": "GET", "requestPrams": "dd" }
import 'package:json_annotation/json_annotation.dart'; // result.g.dart 将在我们运行生成命令后自动生成 part 'result.g.dart'; ///这个标注是告诉生成器,这个类是需要生成Model类的 @JsonSerializable() class Result { //定义构造方法 Result(this.code, this.method, this.requestPrams); //定义字段 int code; String method; String requestPrams; //固定格式,不同的类使用不同的mixin即可 factory Result.fromJson(Map<String, dynamic> json) => _$ResultFromJson(json); //固定格式 Map<String, dynamic> toJson() => _$ResultToJson(this); }
因为实体类的生成代码还不存在,所以上代码会提示一-些错误是正常现象
执行build生成实体类
flutter packages pub run build_runner build