Flutter json数据解析

手动序列化

使用dart:convert手动序列化数据

json数据:

1
2
3
4
{
"name": "John Smith",
"email": "john@example.com"
}

使用jsonDecode()方法来解析json数据

1
2
3
Map<String, dynamic> user = jsonDecode(jsonString);

print(user['name']);

但是这样解析会存在一个问题,就是会失去静态类型的语言特性就是类型安全

模型类中序列化json数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import 'dart:convert';

class User {
final String name;
final String email;

User({this.name, this.email});
User.fromJson(Map<String, dynamic> json)
: name= json['name'],
email= json['email'];

Map<String, dynamic> toJson() => {
'name': name,
'email': email
};
}

void main(List<String> args) {
String jsonString = "{\"name\": \"ctl\", \"email\": \"1111222\"}";
Map userMap = jsonDecode(jsonString);
var user = User.fromJson(userMap);

print('Howdy, ${user.name}!');
print('We sent the verification link to ${user.email}.');
}

与dio库结合

模型类:

1
2
3
4
5
6
7
class OneModel {
final id;

OneModel({this.id});

OneModel.fromJson(Map<String, dynamic> json) : id = json['id'];
}

请求类:

因为dio请求过来的数据已经是map类型了,所以不需要jsonDecode进行编码,直接调用模型类即可解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class RequestImage {
final String url = "http://v3.wufazhuce.com:8000/api/channel/one/0/北京";

Future getImage() async {
try {
Response response = await Dio().get(url);
print(response.data.runtimeType);
// Map dataMap = jsonDecode(response.data['data']);

var user = OneModel.fromJson(response.data['data']);
print(user.id);
} catch (e) {
print(e);
}
}
}
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2017-2021 More Star

请我喝杯咖啡吧~

支付宝
微信