2009-12-05 68 views
0

我想創建一個Http請求並將結果存儲在一個JSONObject中。我沒有用servlet工作太多,所以我不確定我是否1)正確地創建請求,2)應該創建JSONObject。我已經導入了JSONObject和JSONArray類,但是我不知道應該在哪裏使用它們。以下是我的:如何從Java Servlet中檢索JSON中的提要?

 public void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws IOException { 

     //create URL  
     try { 
      // With a single string. 
      URL url = new URL(FEED_URL); 

      // Read all the text returned by the server 
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
      String str; 
      while ((str = in.readLine()) != null) { 
       // str is one line of text; readLine() strips the newline character(s) 
      } 
      in.close(); 
     } catch (MalformedURLException e) { 
     } 
     catch (IOException e) { 
     } 

我的FEED_URL已經寫好,它會返回格式爲JSON的提要。

這已經讓我幾個小時了。非常感謝,你們是非常寶貴的資源!

回答

2

首先收集響應爲一個字符串:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
StringBuilder fullResponse = new StringBuilder(); 
String str; 
while ((str = in.readLine()) != null) { 
    fullResponse.append(str); 
} 

然後,如果字符串以 「{」 開始,你可以使用:

JSONObject obj = new JSONObject(fullResponse.toString()); //[1] 

,如果它以 「[」 開始,你可以使用:

JSONArray arr = new JSONArray(fullResponse.toStrin()); //[2] 

[1] http://json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29

[2] http://json.org/javadoc/org/json/JSONArray.html#JSONArray%28java.lang.String%29

0

首先,這實際上不是servlet問題。您在使用javax.servlet API時沒有任何問題。您在java.net API和JSON API中遇到問題。

對於解析和格式化JSON字符串,我建議使用Gson(Google JSON)而不是傳統的JSON API。它更好地支持泛型和嵌套屬性,並且可以在一次調用中將JSON字符串轉換爲完全可用的javabean。

我已經在here之前發佈了一個完整的代碼示例。希望你覺得它有用。