本篇文章為大家展示了使用Flutter怎么對JSON進行解析,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
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}');安裝插件
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);
}因為實體類的生成代碼還不存在,所以上代碼會提示一-些錯誤是正?,F象
執行build生成實體類
flutter packages pub run build_runner build

上述內容就是使用Flutter怎么對JSON進行解析,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。