我试图从HTTP响应中获取JSONObject。

try
    {
        GetMethod postMethod = new GetMethod();
        postMethod.setURI(new URI(url, true));
        postMethod.setRequestHeader("Accept", "application/json");
        httpClient.executeMethod(postMethod);
        String resp=postMethod.getResponseBodyAsString();
        org.json.JSONTokener tokener = new org.json.JSONTokener(resp);
        finalResult = new org.json.JSONArray(tokener);

        return finalResult;
    }

但是我收到了运行时警告



是否应该按照JVM的建议将响应作为流发送?如果是这样,我如何从中解析JSON?

最佳答案

如果要从服务器假设发送jsonObjects(tomcat服务器)

对于服务器端-

创建jsonobjects-

我将toJson()称为创建jsonobjects,这是实现-

final JSONObject arr = new JSONObject();

for (int i = 0; i < contactStatus.size(); i++) {
    ContactStatus contactObject = contactStatus.get(i);

    try {
        arr.put(String.valueOf(i), toJson(value1, value2,, value3));
    } catch (JSONException e) {

     catch block e.printStackTrace();
    }
}

//Here we serialize the stream to a String.
final String output = arr.toString();
response.setContentLength(output.length());
out.print(output);//out is object of servlet output stream.

public static Object toJsonForContact(String value1, boolean value2, double value3) throws JSONException {

    JSONObject contactObject = new JSONObject();
    contactObject.put("id", id);
    contactObject.put("status", value1);
    contactObject.put("distance", value2);
    contactObject.put("relation", value3);
    return contactObject;
}

因此,您的jsonobjects已准备好发送,我们将这些对象写入ServletoutputStream

在客户端-
while ((ReadResponses = in.readLine()) != null) {
        Constants.Response_From_server = ReadResponses;

        if (Constants.Response_From_server.startsWith("{")) {
            ListOfContactStatus = new ArrayList<ContactStatus>();
            ContactStatus contactStatusObject;

            try {
                JSONObject json = new JSONObject(Constants.Response_From_server);

                for (int i = 0; i < json.length(); i++) {
                    contactStatusObject = new ContactStatus();

                    JSONObject json1 = json.getJSONObject(String.valueOf(i));
                    System.out.println("" + json1.getString("id"));
                    System.out.println("" + json1.getBoolean("status"));
                    System.out.println("" + json1.getDouble("distance"));

                    contactStatusObject.setId(json1.getString("id"));
                    contactStatusObject.setStatus(json1.getBoolean("status"));
                    contactStatusObject.setDistance((float) json1.getDouble("distance"));
                    ListOfContactStatus.add(contactStatusObject);
                    System.out.println("HTTPTransport:sendMessage  Size of ListOfContactStatus" + ListOfContactStatus.size());
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

10-08 02:01