flutter_JSON序列化
json_encode是将数值转换成json格式,json_decode()函数将json数据转换成数组
要序列化一个ServiceInfoModel ,我们只是将该ServiceInfoModel 对象传递给该JSON.encode方法。我们不需要手动调用toJson这个方法,因为JSON.encode已经为我们做了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class User { User(this.id, this.name);
int id; String name;
User.fromJson(Map<String, dynamic> json) { id = json['id']; name = json['name']; }
Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['name'] = this.name; return data; } }
|
进行jsonencode 和jsondecode进行编码解码
1 2 3 4 5 6 7 8 9 10 11 12
| Future<User> login(String mobile, String sms) async { User user = User(1, '程序员磊哥'); print('登录成功: $user'); var data = jsonEncode(user); print("jsonEncode转换的结果对象转为json过程" + data); Map user2 = jsonDecode(data.toString()); print("jsonDecode转换的结果为map并得到map的id值为" + user2["id"].toString()); User user3 = User.fromJson(jsonDecode(data.toString())); print("jsonDecode转换的结果为map再用 User.fromJson(string)转为对象use" + user3.name); return user; }
|
1 2 3 4 5
| I/flutter (17450): jsonEncode转换的结果对象转为json过程{"id":1,"name":"程序员磊哥"} I/flutter (17450): jsonDecode转换的结果为map并得到map的id值为1 I/flutter (17450): jsonDecode转换的结果为map再用 User.fromJson(string)转为对象use程序员磊哥 I/flutter (17450): 加载首页数据... I/flutter (17450): 加载首页数据完成
|
加载本地json文件
在pubspec.yaml中添加
1 2
| assets: - assets/personnel.json
|
1 2 3 4 5 6 7 8 9
| import 'dart:convert'; import 'package:flutter/services.dart';
class JsonUtil { static Future<Map<String, dynamic>> getJsonData(String fileName) async { String jsonStr = await rootBundle.loadString('assets/' + fileName); return jsonDecode(jsonStr); } }
|