The following is a test code, in which I am trying to post some query via google api, the api should send the response in json parseable string. When I print the string I clearly see the entities such as url, but when I try to get these entities from JSON Object, I get the error.
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();
}
}
}
it throws following exception:
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)
Any help is highly appreciated.