将JSON作为输入时,MongoDB为NULL指针异常

时间:2014-03-07 10:14:04

标签: java mongodb database

package com.demo.mongodb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;

public class Driver {
    private static DBCollection channelDBcollection;

    public static void main(String[] args) throws IOException {
        DB db = (new MongoClient("localhost",27017)).getDB("demo");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        boolean flag = false;
        while(!flag) flag = autenticate(db, bufferedReader);
    }
    private static boolean autenticate(DB db, BufferedReader bufferedReader) throws IOException{
        boolean flag = true;
        System.out.println("User: ");
        String user = bufferedReader.readLine();

        System.out.println("Password: ");
        String password = bufferedReader.readLine();

        if(db.authenticate(user, password.toCharArray())){
            DBCollection channDbCollection = db.getCollection("Channel");
            String command = null;
            while(true){
                System.out.println("What do you want to do ? ");
                command = bufferedReader.readLine();
                if(command.equals("exit")) break ;
                else if(command.equals("findALL")) findAll(channDbCollection);
                else if(command.equals("insertJSON")) insertJSON(bufferedReader,channDbCollection);
            }
        }
        else{
            System.out.println("invalid user/password");
            flag = false;
        }


        return flag;
    }

    private static void findAll(DBCollection dbCollection){
        DBCursor dbCursor = channelDBcollection.find();
        while(dbCursor.hasNext()) System.out.println(dbCursor.next());
    }

    private static void insertJSON(BufferedReader bufferedReader,DBCollection channDbCollection) throws IOException {

        System.out.println("JSON: ");
        channDbCollection.insert((DBObject) JSON.parse(bufferedReader.readLine()));
    }
}

我在MongoDB中创建数据库,如: -

  

使用演示

     

db.addUser( “根”, “根”)

当我执行应用程序然后当我输入JSON时,我发现空指针有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

中的

private static void findAll(DBCollection dbCollection){
    DBCursor dbCursor = channelDBcollection.find();
    while(dbCursor.hasNext()) System.out.println(dbCursor.next());
}

函数,您使用全局变量channelDBcollection(在调用时为null)而不是参数dbCollection(在方法中的任何地方都不使用); 您认为“非空”的是具有混淆名称“channDbCollection”的局部变量,但它并未在任何地方使用;

我建议你修改你的命名方法,一般使用全局变量和编码风格。