An inbox JSON object cannot be initialized?
I'm trying to create a JSON inbox object in Java.
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.o开发者_C百科ut.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();
}
}
}
But I got the following error message:
The local variable messages have not been initialzied
What have I done wrong?
The JSON classes I use is the original ones in http://www.json.org/java/
BTW, I'm using Eclipse as my IDE
Ok, I think I located the problem. The JSON library I added got an error when I tried to export the Jar file. And the error appeared in JSONArray class. How do you export JSON library to jar files in Eclipse?
This is how I did and got some warning(The warning was in the JSONArray class):
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
Never mind the location of the problem. I tried to define instead the variable messages the variable messagesss
as a JSONArray obj. I still got the same error with message
not messagessss
. But how do I correct this problem?
The java class is under a package called messages, is this the problem?
If clean+build can't help try to refresh your project or restart you IDE. I copy this code in my Eclipse and there are not any problems.
精彩评论