HelloWorld
HelloWorld

Reputation: 47

MongoCollection to JSON array

After going through tons of examples, I couldn't find relevant code, Basically I want to serialize the JSON array over the wire to the client.

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;

Attempt Doesn't work but is something close to what I'm looking for.

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();

Any serialization solutions for mongodb collections?

Naive way works

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

Upvotes: 0

Views: 910

Answers (2)

Vokail
Vokail

Reputation: 691

I assume your desired output value is not an "infinite json", otherwise put in place some kind of pagination.

Basically with java mongo driver you have a org.bson.Document class, and with method toJson you create a string with inside Json for your Document, reference: https://api.mongodb.com/java/3.2/org/bson/Document.html#toJson--

Note: basic encoder take care of handling arrays for you

Upvotes: 0

Ben Benson
Ben Benson

Reputation: 336

I'm using com.fasterxml.jackson.databind.ObjectMapper for this purpose.

Upvotes: 1

Related Questions