从MongoDB集合中输出json的正确有效方法是什么?

时间:2014-05-28 12:57:59

标签: java json mongodb

下面你会看到一个与我的mongodb收集数据服务风格相关的样本,它可以工作,但我刚刚连接了不好的字符串,因此对我来说似乎不正确,我已经检查了对于它在网上,但看不到任何东西,如果有人知道请与我分享。

@Path("/getdata/{collectionName}/{count}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getData(@PathParam("collectionName") String collectionName, @PathParam("count") int count) throws UnknownHostException{
    DB db = (new MongoClient("localhost")).getDB("testdb");
    DBCollection dbCollection = db.getCollection(collectionName);
    BasicDBObject basicDBObject = new BasicDBObject();
    basicDBObject.put("name", "mustafa");
    DBCursor dbCursor = dbCollection.find(basicDBObject);
    String result = "{\" "+ collectionName +" \": [";

    int i = 0;
    while(dbCursor.hasNext() && i < count){
        result += dbCursor.next() + ", ";
        i++;
    }

    result = result.substring(0,result.length()-2);
    result += "]}";
    return result;
}

1 个答案:

答案 0 :(得分:0)

您可以使用com.mongodb.util.JSON.serialize()方法将对象序列化为JSON并返回。

相关问题