gpt4 book ai didi

json - 我如何将我的类(class)编码为 json 以将 http put 发送到 firebase

转载 作者:IT老高 更新时间:2023-10-28 12:45:00 25 4
gpt4 key购买 nike

我正在尝试对我的类进行编码以将一个 put http 发送到 firebase,但是当我打印 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()};
}

关于json - 我如何将我的类(class)编码为 json 以将 http put 发送到 firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54184952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com