dart:convert 库提供了对json的支持
jsonDecode可以将json字符串转换为Map,jsonEncode可以将对象序列化为json字符串
import 'dart:convert';
void main(){
String jsonString = '{"name":"John Smith","email":"john@example.com"}';
Map<String, dynamic> userMap = jsonDecode(jsonString);
print(userMap);// {name: John Smith, email: john@example.com}
print(jsonEncode(userMap));// {"name":"John Smith","email":"john@example.com"}
}
同时,提供了对类的序列化支持
创建一个模型类
为模型类添加fromJson的构造方法,以及toJson方法
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(){
String jsonString = '{"name":"John Smith","email":"john@example.com"}';
Map<String, dynamic> userMap = jsonDecode(jsonString);
User user = User.fromJson(userMap);//使用fromJson方法解码,获取一个User的实例
print(jsonEncode(user));//使用jsonEncode方法将User的实例编码成字符串
}