Flutter解析JSON 浅谈Flutter解析JSON三种方式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Flutter解析JSON 浅谈Flutter解析JSON三种方式

静默的小猫   2021-03-30 我要评论
想了解浅谈Flutter解析JSON三种方式的相关内容吗,静默的小猫在本文为您仔细讲解Flutter解析JSON的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Flutter解析JSON,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

如何选择


猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们