json - 我如何将我的课程编码为 json 以将 http put 发送到 firebase
问题描述
我正在尝试对我的类进行编码以向 firebase 发送一个 put http,但是当我打印 User.toMap 时,我的函数显示了一个带有“'Address' 实例”的列表。
{id: -LVsaRJKo3vo6q9NWZn_, name: User 38197, email: null, address: [Instance of 'Address']}
class User {
String id;
String name;
String email;
List<Address> address = new List<Address>();
User({this.id, this.name, this.email, this.address});
User.fromMap(Map<String, dynamic> map) {
this.id = map['id'];
this.name = map['name'];
this.email = map['email'];
if (map['address'] == null) {
this.address = new List<Address>();
} else {
this.address= (map['address'] as List).map((i) => Address.fromMap(i)).toList();
}
}
Map<String, dynamic> toMap() {
return {'id': id, 'name': name, 'email': email, 'address': address};
}
}
===
class Address {
String test;
Address ({this.test});
Address.fromMap(Map<String, dynamic> map) {
this.test = map['test'];
}
Map<String, dynamic> toMap() {
return {
'test': test
}
}
===
在类 ApiProvider
Future<User> updateUser(User userUpdate) async {
String id = userUpdate.id;
print(userUpdate.toMap()); // This prints that line
final http.Response response = await http.put(
baseUrl + '/user/$id.json',
body: json.encode(userUpdate.toMap()), // Here happens the error
);
final Map<String, dynamic> userData = json.decode(response.body);
User user = new User.fromMap(userData);
return user;
}
===
最后的错误:
I/flutter (17495): {id: -LVsaRJKo3vo6q9NWZn_, name: User 38197, email: null, address: [Instance of 'Address']}
E/flutter (17495): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (17495): Converting object to an encodable object failed: Instance of 'Address'
E/flutter (17495): #0 _JsonStringifier.writeObject (dart:convert/json.dart:703:7)
E/flutter (17495): #1 _JsonStringifier.writeList (dart:convert/json.dart:753:7)
E/flutter (17495): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:735:7)
E/flutter (17495): #3 _JsonStringifier.writeObject (dart:convert/json.dart:693:9)
E/flutter (17495): #4 _JsonStringifier.writeMap (dart:convert/json.dart:786:7)
E/flutter (17495): #5 _JsonStringifier.writeJsonValue (dart:convert/json.dart:741:21)
E/flutter (17495): #6 _JsonStringifier.writeObject (dart:convert/json.dart:693:9)
解决方案
Map<String, dynamic> toMap() {
return {'id': id, 'name': name, 'email': email, 'address': address};
}
需要改为
Map<String, dynamic> toMap() {
return {'id': id, 'name': name, 'email': email, 'address': address.map((a) => a.toMap()).toList()};
}
推荐阅读
- maven - 连接超时:在 Maven 中从 Nexus 下载时连接错误
- python - WebDriverException:消息:TypeError:无法访问死对象
- mysql - 返回表MYSQL的过程或函数
- html - CSS - 优化同一项目的恒定屏幕尺寸变化以提高性能
- linux - 每日 grep 和输出状态
- php - 从数据库中选择带有信息的选项
- asp.net - 使用 Azure 上的现有数据库部署 ASP MVC 应用程序
- angularjs - 无法在数字“1”上创建属性“路线”
- python - 如何使用模糊逻辑从熊猫数据框中匹配和提取文本?
- java - 有什么方法可以在使用 selenium 的 Web 自动化测试中获取请求正文?