以下是一个测试代码,我在其中尝试通过 google api 发布一些查询,api 应该以 json 可解析字符串发送响应。当我打印字符串时,我清楚地看到了诸如 url 之类的实体,但是当我尝试从 JSON 对象中获取这些实体时,我得到了错误。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;
public class test {
public static void main (String[] args) {
try {
// The request also includes the userip parameter which provides the end
// user's IP address. Doing so will help distinguish this legitimate
// server-side traffic from traffic which doesn't come from an end-user.
URL url = new URL(
"https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=lahore");
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
System.out.println(line);
}
JSONObject jsonObject = new JSONObject(builder.toString());
System.out.println(jsonObject);
String url1 = (String) jsonObject.get("url");
System.out.println(url1);
} catch(Exception e) {
e.printStackTrace();
}
}
}
它抛出以下异常:
org.json.JSONException: JSONObject["url"] not found.
at org.json.JSONObject.get(JSONObject.java:459)
at org.json.JSONObject.getJSONArray(JSONObject.java:540)
at test.main(test.java:37)
非常感谢任何帮助。