0

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I'm trying to find oracle json library solution
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.