【发布时间】:2014-09-29 18:19:17
【问题描述】:
我正在尝试将一些数据从 dart 项目发布到另一个项目并将它们存储在 mongoDB 中
邮政编码:
import 'dart:io';
void main() {
List example = [
{"source": "today", "target": "tomorrow"},
{"source": "yesterday", "target": "tomorrow"},
{"source": "today", "target": "yesterday"}
];
new HttpClient().post('localhost', 4040, '')
.then((HttpClientRequest request) {
request.headers.contentType = ContentType.JSON;
request.write(example);
return request.close();
});
}
接收它的代码,在另一个文件中
void start() {
HttpServer.bind(address, port)
.then((HttpServer server) {
// Log in console to show that server is listening
print('Server listening on ${address}:${server.port}');
server.listen((HttpRequest request) {
request.transform(UTF8.decoder).listen(sendToDatastore);
});
});
}
void sendToDatastore(String contents) {
var dbproxy = new dbProxy("myDb");
dbproxy.write("rawdata", contents);
index++;
// non related to the problem code
}
bool write(collectionName, document)
{
Db connection = connect();
DbCollection collection = connection.collection(collectionName);
connection.open().then((_){
print('writing $document to db');
collection.insert(document);
}).then((_) {
print('closing db');
connection.close();
});
return true;
}
我正在努力解决的是我正在使用
request.transform(UTF8.decoder).listen(sendToDatastore);
所以我将请求流转换为字符串,因为我找不到将其作为 Json 发送的方式。
然后在 sendToDatastore 中我无法正确解析它以存储它。据我了解,当我遇到此错误时,我需要将每个 Json 对象作为 Map 来存储它
Uncaught Error: type 'String' is not a subtype of type 'Map' of 'document'.
谢谢,
更新
如果我尝试在 sendToDatastore 中执行类似的操作
void sendToDatastore(String contents) {
var dbproxy = new dbProxy("myDb");
var contentToPass = JSON.decode(contents);
contentToPass.forEach((element) => dbproxy.write("rawdata", element));
index++;
// non related to the problem code
}
它引发了这个错误
Uncaught Error: FormatException: Unexpected character (at character 3)
[{source: today, target: tomorrow}, {source: yesterday, target: tomorrow}, ...
^
在使用 JSON.decode
更新2
错误是我没有从“邮政编码”发送实际的 Json。我用过
// ...
request.write(JSON.encode(example));
// ...
一切正常
谢谢
【问题讨论】:
-
我没有看到你使用
JSON.encode。还有rates在服务器端来自哪里?写入流时,您可以只使用JSON.encode(example)而不是rates。 -
对不起@Robert,rates/example 是一个错误,因为 rates 对象太大我以相同的方式创建了示例,但忘记在调用中更改它。关于 JSON.enconde,它的使用不在我粘贴的第一个代码中,尽管它是我尝试过的,但更新是我尝试使用它时遇到的错误。
-
api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/… - 您不能直接将列表传递给 write 函数。您必须通过 JSON.encode 显式转换它。在接收方,您应该读取全部内容,将字符串转换为对象并自己调用函数。
-
是的,谢谢@Robert,在重新阅读您之前的评论后知道了。我沉迷于“接收”部分。 “更新”代码只需更改邮政编码以传递 JSON.encode
-
如果您将
request.write(example);更改为`request.write(JSON.encode(example));? The error comes from the message being just the.toString()` 列表的结果,问题会消失吗,@987654335 @ 在键上,而不是字符串转义,因此字符串值不被引用,因为它们应该在 JSON 中。