参考:
https://book.flutterchina.club/chapter11/json_model.html
https://segmentfault.com/a/1190000037784724
免费的API文档:https://docs.tenapi.cn/yiyan.html
更新 2021-07-07:
使用这个json2dart生成网页,可以省去自己手动添加注解等工作,推荐!
https://czero1995.github.io/json-to-model/
对于简单的json,手写model类还是比较轻松的,如下代码所示。但还是觉得麻烦呀,对吧!
请求api: https://tenapi.cn/yiyan/?format=json
返回的json内容:
{ "id": "1417957784686", "hitokoto": "梦+想=梦想,这个等式是不成立的。", "cat": "e", "catname": "原创", "author": "明九", "source": "原创", "date": "1417957784" }
class NoteModel {
String? id;
String? hitokoto;
String? cat;
String? catname;
String? author;
String? source;
String? date;
NoteModel(
{this.id,
this.hitokoto,
this.cat,
this.catname,
this.author,
this.source,
this.date});
factory NoteModel.fromJSON(Map<String, dynamic> json){
return NoteModel(
id:json['id'],
hitokoto:json['hitokoto'],
cat:json['cat'],
catname:json['catname'],
author:json['author'],
source:json['source'],
date:json['date'],
);
}
//String json = json.encode(model);
Map<String, dynamic> toJson() => <String, dynamic>{
'id': id,
'hitokoto': hitokoto,
'cat': cat,
'catname': catname,
'author': author,
'source': source,
'date': date,
};
}
}
复杂Json的model类
请求API: https://tenapi.cn/douyinresou/
返回Json内容:
{ "data": 200, "list": [ { "name": "农村国宝回应被警察带走", "hot": 9593623 }, { "name": "詹姆斯称两年来第一次吃红肉", "hot": 8669071 }, { "name": "那年年少飙唱挑战", "hot": 8569888 }, { "name": "12只鲸鱼搁浅浙江头门港海域", "hot": 8420821 }, { "name": "为什么很多人还相信哈维尔2027", "hot": 8334582 }, { "name": "鲸鱼连续多日现身深圳大鹏湾", "hot": 8023050 }, { "name": "硕士录取通知书能有多敷衍", "hot": 7970329 }, { "name": "歪嘴笑挑战", "hot": 7968655 }, { "name": "蔡徐坤与黄旭熙热舞", "hot": 7835599 }, { "name": "一时间不知道听歌还是看脸", "hot": 7831299 } ] }
遇到稍微复杂的,就觉得更麻烦了,手写花时间不说,出错了还要掉头发,是时候寻求快捷轻松的方式了。
食谱:自动生成Model - json_serializable package
引入以下三个依赖
dependencies:
json_annotation: ^4.0.1
dev_dependencies:
json_serializable: ^4.1.3
build_runner: ^2.0.5
把json文本复制到以下网页,获得生成的model类代码:
https://jsonformatter.org/json-to-dart
把dart代码拷贝到项目中新建的model类文件,修缮一下类名,并添加如下代码:
//这里要修改为对应的model类文件名
part 'douyin_hot_model.g.dart';
//添加类注解
@JsonSerializable(explicitToJson: true)
//添加json转换函数(类名修改为相对应的类名)
factory Douyin.fromJson(Map<String, dynamic> json) => _$DouyinFromJson(json);
Map<String, dynamic> toJson() => _$DouyinToJson(this);
最终效果:
douyin_hot_model.dart
import 'package:json_annotation/json_annotation.dart';
part 'douyin_hot_model.g.dart';
@JsonSerializable(explicitToJson: true)
class Douyin {
final int? data;
final List<ListElement>? list;
Douyin({
this.data,
this.list,
});
factory Douyin.fromJson(Map<String, dynamic> json) => _$DouyinFromJson(json);
Map<String, dynamic> toJson() => _$DouyinToJson(this);
}
@JsonSerializable()
class ListElement {
final String? name;
final int? hot;
ListElement({
this.name,
this.hot,
});
factory ListElement.fromJson(Map<String, dynamic> json) => _$ListElementFromJson(json);
Map<String, dynamic> toJson() => _$ListElementToJson(this);
}
记得执行一下以下命令,以生成douyin_hot_model.g.dart
文件
flutter pub run build_runner build
然后就可以愉快地食用了
Future<Douyin> getDouyin() async {
var url = Uri.parse('https://tenapi.cn/douyinresou/');
final response = await http.get(url);
var result = json.decode(Utf8Decoder().convert(response.bodyBytes));
return Douyin.fromJson(result);
}
buildDouyinUi(Douyin douyin) {
List<Text> items = [];
var list = douyin.list;
list!.forEach((element) {
items.add(Text(
'《${element.name}》\n热度:${element.hot}',
style: TextStyle(fontSize: 20),
));
});
return Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: items,
),
);
}
有更好更方便的方法,记得留言哦~
后期如果执行该命令出现如下错误:
flutter pub run build_runner build
出错啦------
flutter pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 336ms
[WARNING] Deleted previous snapshot due to missing asset graph.
[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 12.5s
[INFO] Initializing inputs
[INFO] Building new asset graph...
[INFO] Building new asset graph completed, took 787ms
[INFO] Checking for unexpected pre-existing outputs....
[INFO] Found 13 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
[SEVERE] Conflicting outputs were detected and the build is unable to prompt for permission to remove them. These outputs must be removed manually or the build can be run with `--delete-conflicting-outputs`. The outputs are: lib/models/advisory-service-item.g.dart
如下方式可以解决
flutter packages pub run build_runner build --delete-conflicting-outputs
如果不行的话:
File => Invalidate caches / Restart
flutter clean
flutter pub get
flutter packages pub run build_runner build --delete-conflicting-outputs