有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java收件箱JSON对象无法初始化?

我正在尝试用Java创建一个JSON收件箱对象

 public class GetContacts extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
    try{
        String list = req.getParameter("list");
        String profileId = "27";
        //Accessing driver from the JAR file 
        Class.forName ("com.mysql.jdbc.Driver").newInstance();  

        //Connect to Clockie's database
        Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/cdatabase", "root", "root");

        //Here we create our query
        String sql =
                "SELECT * " +
                "FROM messages " +
                "WHERE profileId = ?";
        PreparedStatement statement = con.prepareStatement(sql);
        statement.setString(1, profileId);
        ResultSet result = statement.executeQuery();
        JSONArray messages = new JSONArray();
        while(result.next()){
            JSONObject message = new JSONObject();
            message.put("to", result.getString("to"));
            message.put("from", result.getString("from"));
            message.put("message", result.getString("message"));
            message.put("profileId", profileId);
            messages.put(message);
        }
        System.out.println(messages.toString());


        resp.setContentType("text/javascript");
        PrintWriter out = resp.getWriter();
        String output = req.getParameter("callback") + "(" + messages.toString() + ");";
        out.write(output);
        out.close();

    }
    catch(Exception e){
        e.printStackTrace();
    }
}
}

但我收到了以下错误消息:

The local variable messages have not been initialzied

我做错了什么

我使用的JSON类是http://www.json.org/java/中的原始类

顺便说一句,我使用Eclipse作为我的IDE

好的,我想我找到了问题所在。我添加的JSON库在尝试导出Jar文件时出错。错误出现在JSONArray类中。在Eclipse中如何将JSON库导出到jar文件

我就是这样做的,并得到了一些警告(警告出现在JSONArray类中):

Ok created a new project and right click -> export -> choose Jar Files (under java folder) -> marked both .classpath and .project in the right rectangle -> I selected a random destination folder with the filname org.json.jar. When I did this i got some warnings

不要在意问题的位置。我尝试将变量消息messagesss定义为JSONArray对象。我仍然在message而不是messagessss上遇到同样的错误。但是我如何纠正这个问题呢

java类在一个名为messages的包下,这就是问题所在吗


共 (1) 个答案

  1. # 1 楼答案

    如果clean+build无法帮助您刷新项目或重新启动IDE。我在Eclipse中复制了这段代码,没有任何问题