软件编程
位置:首页>> 软件编程>> Android编程>> 浅谈Flutter解析JSON三种方式

浅谈Flutter解析JSON三种方式

作者:静默的小猫  发布时间:2022-04-08 10:46:45 

标签:Flutter,解析,JSON

Dart实体类格式


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}');

方案二:生产力工具:json-to-dart插件自动生成实体类

方案三:生产力工具: json_ serializable使用技巧

安装插件


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

如何选择

浅谈Flutter解析JSON三种方式

来源:https://juejin.cn/post/6944876239425536036

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com