2011-02-28 3 views
0

자바에서 JSON받은 편지함 객체를 만들려고합니다.받은 편지함 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으로 클래스 내 IDE로

좋아 Eclipse를 사용하고, BTW http://www.json.org/java/

원래 사람이다, 나는이 문제에 위치해 생각합니다. Jar 파일을 내보낼 때 내가 추가 한 JSON 라이브러리에 오류가 발생했습니다. 그리고 JSONArray 클래스에 오류가 나타났습니다. Eclipse에서 JSON 라이브러리를 jar 파일로 어떻게 내 보냅니 까?

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

문제의 위치를 ​​신경 쓰지 :

이것은 내가 한 몇 가지 경고를 가지고 (경고는 JSONArray 클래스에 있었다) 방법이다. 변수 메시지 대신 변수 messagesss을 JSONArray obj로 정의하려고했습니다. 여전히 message이 아닌 messagessss과 같은 오류가 발생합니다. 그러나이 문제를 어떻게 수정합니까?

Java 클래스가 messages라는 패키지 아래에 있는데, 이것이 문제입니까?

+0

이상하게 들리지만 내게 맞습니다. – jjnguy

+0

은 배열을 초기화하는이 줄이 아닙니다. > JSONArray messages = new JSONArray(); – einstein

+0

@Woh, yup. 그것이 내가 문제가 있어야한다고 생각하지 않는 이유입니다. 당신은 깨끗한 짓을 했습니까? – jjnguy

답변

0

clean + build가 프로젝트를 새로 고치거나 IDE를 다시 시작하는 데 도움이되지 않으면. 내 이클립스 에서이 코드를 복사하고 아무런 문제가 없습니다.

+0

프로젝트를 새로 고치는 방법과 빌드를 정리하는 방법은 무엇입니까? Eclipse btw를 사용하고 있습니다. 그들은 자동으로 구축? – einstein

+0

다른 문제가 있다고 생각합니다. 이름이 같은 여러 변수가 있습니다. 질문 주석을 확인하십시오. –

+0

그게 문제라고 생각하지 않습니다. 최소한 나는 메시지라는 변수가 더 이상 없다는 것을 알 수있다. – einstein

관련 문제