亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

淺談Flutter解析JSON三種方式

 更新時(shí)間:2021年03月30日 11:34:11   作者:靜默的小貓  
這篇文章主要介紹了淺談Flutter解析JSON三種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

Dart實(shí)體類格式

class CategoryMo {
 String name;
 int count;

 CategoryMo({this.name, this.count});
 //將map轉(zhuǎn)成mo
 CategoryMo.fromJson(Map<String, dynamic> json) {
 name = json['name'];
 count = json['count'];
 }
 //將mo轉(zhuǎn)成map,可缺省
 Map<String, dynamic> toJson() {
 final Map<String, dynamic> data = new Map<String, dynamic>();
 data['name'] = this.name;
 data['count'] = this.count;
 return data;
 }
}

方案一:手寫實(shí)體類

person.json

{
 "name": "Jack",
 "age": 20
}

model轉(zhuǎn)換與使用

var personMap = {
 "name": "Jack",
 "age": 20
};
Person person = Person.fromJson(personMap);
print('name:${person.name}');
print('age:${person.age}');

方案二:生產(chǎn)力工具:json-to-dart插件自動生成實(shí)體類

方案三:生產(chǎn)力工具: json_ serializable使用技巧

安裝插件

dependencies:
...
 dio: ^3.0.10
 json_annotation: ^3.1.0


dev_dependencies:
...
 json_serializable: ^3.5.0
 build_runner: ^1.0.0

配置實(shí)體類

{
 "code": 0,
 "method": "GET",
 "requestPrams": "dd"
}
import 'package:json_annotation/json_annotation.dart';

// result.g.dart 將在我們運(yùn)行生成命令后自動生成
part 'result.g.dart';

///這個(gè)標(biāo)注是告訴生成器,這個(gè)類是需要生成Model類的
@JsonSerializable()
class Result {
 //定義構(gòu)造方法
 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);
}

因?yàn)閷?shí)體類的生成代碼還不存在,所以上代碼會提示一-些錯(cuò)誤是正?,F(xiàn)象

執(zhí)行build生成實(shí)體類

flutter packages pub run build_runner build

如何選擇


到此這篇關(guān)于淺談Flutter解析JSON三種方式的文章就介紹到這了,更多相關(guān)Flutter解析JSON內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論