gpt4 book ai didi

java - MongoCollection 到 JSON 数组

转载 作者:行者123 更新时间:2023-12-02 09:39:26 26 4
gpt4 key购买 nike

在经历了大量的examples之后,我找不到相关代码,基本上我想通过线路将 JSON 数组序列化到客户端。

MongoCursor<Document> cursor = ((MongoCollection)data).find().iterator();
try {
while (cursor.hasNext()) {
response.getWriter().write(cursor.next().toJson());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
cursor.close();
}
break;
<小时/>

尝试不起作用,但与我正在寻找的东西很接近。

MongoCursor<Document> cursor = ((MongoCollection)data).find().iterator();
JsonWriter jsonWriter = new JsonWriter(response.getWriter());
jsonWriter.writeStartDocument();
jsonWriter.writeStartArray();

while(cursor.hasNext()) {
jsonWriter.writeStartDocument();
jsonWriter.writeString(cursor.next().toJson());
jsonWriter.writeEndDocument();
}

jsonWriter.writeEndArray();
jsonWriter.writeEndDocument();

cursor.close();

有针对 mongodb 集合的序列化解决方案吗?

天真的方式有效

try {
response.getWriter().write("[");
while (cursor.hasNext()) {
response.getWriter().write(cursor.next().toJson() + (cursor.hasNext() ? "," : ""));
}
response.getWriter().write("]");
} finally {
cursor.close();
}

最佳答案

我正在使用 com.fasterxml.jackson.databind.ObjectMapper 来实现此目的。

关于java - MongoCollection 到 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57220433/

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