有 Java 编程相关的问题?

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

eclipse如何从Javaservlet检索JSON提要?

我想发出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格式的FEED

这件事已经困扰了我好几个小时了。非常感谢你们,你们是无价之宝


共 (2) 个答案

  1. # 1 楼答案

    首先将响应收集到字符串中:

    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

  2. # 2 楼答案

    首先,这实际上不是一个servlet问题。您对javax.servletAPI没有任何问题。您只是在java.netAPI和JSON API方面有问题

    对于JSON字符串的解析和格式化,我建议使用Gson(Google JSON)而不是传统的JSON API。它对泛型和嵌套属性有更好的支持,并且可以在一次调用中将JSON字符串转换为完整的javabean

    我在here之前发布了一个完整的代码示例。希望你觉得有用