flutter 的 json序列化和反序列化
一、json转实体
Instantly parse JSON in any language | quicktype
二、实体中的toJson和fromJson 实现
官方推荐的 两个插件(个人觉得一个实体会多一个.g.dart 文件太多了,不喜欢)
-
json_annotation
-
json_serializable
三、使用 dart_json_mapper 实现上面的功能同时,还可以将接口返回的字符串自动转为指定类型
下面是官网说的好处
在根目录创建 build.yaml 这里是配置入口的地方。
targets:$default:builders:dart_json_mapper:generate_for:# here should be listed entry point files having 'void main()' function- lib/main.dart# This part is needed to tell original reflectable builder to stay away# it overrides default options for reflectable builder to an **empty** set of filesreflectable:generate_for:- no/files
根目录运行,就会生成 main.mapper.g.dart
dart run build_runner build --delete-conflicting-outputs
然后main中引入
import 'main.mapper.g.dart' show initializeJsonMapper;
void main() {initializeJsonMapper();print(JsonMapper.serialize(MyData(456, true, "yes")));
}
第四、使用 dart_mappable
dart_mappable: 简化Dart中的JSON序列化与数据类处理-CSDN博客
第五、使用 freezed
https://zhuanlan.zhihu.com/p/716426189