Java 从mango读取数据转为json并解析

   // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        String DB_NAME = "testdb";
        String DB_COL = "qadata_test";
        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);

        // 获取集合
        MongoCollection mongoCollection = mongoDatabase.getCollection(DB_COL);
        Gson gson = new Gson();
        //从mongo读取数据
        FindIterable findIterable= mongoCollection.find();
        MongoCursor mongoCursor = findIterable.iterator();
        List objects = new ArrayList();
        int n=0;
        while(mongoCursor.hasNext()){
            objects.add(mongoCursor.next());
            n++;
        }

        List searchLogs = new ArrayList();
        //json解析
        for (Object object:objects){
            String json = gson.toJson(object);
            searchLogs.add(gson.fromJson(json,SearchLog.class));
        } 
  

 

你可能感兴趣的:(Java)