我的資源如下給出,我試圖以json格式返回mongo表中的所有文檔。REST風格的服務無法返回正確的JSON格式
@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;
}
這將返回JSON包含:
[{"type":"dbObject"},{"type":"dbObject"}]
但是,當我在控制檯打印出令牌它包含正確的集合,它是:
{
"_id" : ObjectId("55fc4844f7aea67825dae9a1"),
"login_id" : "sam",
"password" : "***"
}
{
"_id" : ObjectId("56110506d7ca91f604065fdc"),
"login_id" : "bam",
"password" : "***"
}
這是我想要什麼它返回。我哪裏錯了,請嘗試提供一個示例,因爲我是RESTful服務的新手。
有一個JSON序列化你試過'return.toString()'含)'String'的返回類型getMongoObject的'('。請參閱[BasicDBObject的API文檔](http://api.mongodb.org/java/2.6/com/mongodb/BasicDBObject.html#toString%28%29) – thegauravmahawar
您的意思是public String getMongoObject(){.... return token.toString();}? –
現在,我試了一下,它的工作原理。哇,我怎麼錯過了。謝謝你的幫助,這是一個相當愚蠢的問題 –