Reputation: 94
My resource is given as follows, I am trying to return all the documents in the mongo table in a json format.
@Path("/myresource")
@GET
@Produces( MediaType.APPLICATION_JSON)
public ArrayList<DBObject> getMongoObject() throws Exception {
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("zapshop");
DBCollection collection = db.getCollection("admin");
DBCursor cursor = collection.find();
DBObject object = cursor.next();
ArrayList<DBObject> token = new ArrayList<DBObject>();
token.add(object);
while (cursor.hasNext()) {
object = cursor.next();
token.add(object);
//System.out.println(token);
}
if (object == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return token;
}
This returns JSON which contains:
[{"type":"dbObject"},{"type":"dbObject"}]
But when i print out token in the console it contains the proper collection, which is :
{
"_id" : ObjectId("55fc4844f7aea67825dae9a1"),
"login_id" : "sam",
"password" : "***"
}
{
"_id" : ObjectId("56110506d7ca91f604065fdc"),
"login_id" : "bam",
"password" : "***"
}
Which is what i want it to return. Where am i going wrong,pls try providing an example as i am new to RESTful services.
Upvotes: 1
Views: 148
Reputation: 2823
You should do:
public String getMongoObject() throws Exception {
.......
.......
return token.toString();
}
From the docs:
toString
public String toString()
Returns a JSON serialization of this object
Upvotes: 1
Reputation: 11
Try this I use GSON to convert from BasicDBObject to my own POJO which is TinyBlogDBObject
TinyBlogDBObject obj = convertJSONToPojo(cursor.next().toString()); private static TinyBlogDBObject convertJSONToPojo(String json){
Type type = new TypeToken< TinyBlogDBObject >(){}.getType();
return new Gson().fromJson(json, type);
}
Upvotes: 0