欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談Flutter解析JSON三種方式

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

Dart實體類格式

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

方案一:手寫實體類

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插件自動生成實體類

方案三:生產(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

配置實體類

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

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

///這個標注是告訴生成器,這個類是需要生成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);
}

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

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

flutter packages pub run build_runner build

如何選擇


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

相關文章

最新評論