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;

//jsonDecode(sting) ->就是fromJson过程 转成结果为map
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}

//jsonEncode(user) ->就是tojson过程
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
return data;
}
}

进行jsonencodejsondecode进行编码解码

1
2
3
4
5
6
7
8
9
10
11
12
/// 用户登录。简单起见,返回User
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);
}
}