簡體   English   中英

如何從Java Servlet檢索JSON中的提要?

[英]How can I retrieve a feed in JSON from a Java Servlet?

我想發出一個Http請求並將結果存儲在JSONObject中。 我在servlet方面工作不多,因此不確定我是否1)正確提出請求,以及2)應該創建JSONObject。 我已經導入了JSONObject和JSONArray類,但是我不知道應該在哪里使用它們。 這是我所擁有的:

     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的供稿。

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

首先將響應收集到一個字符串中:

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

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

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

之前,我已經發布了完整的代碼示例。 希望你覺得它有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM