简体   繁体   中英

JSON error in Java while trying to access google api

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.

After examining the json string:

You can't directly get the "url", to get "url" you would need to do below once you read the stream into the StringBuilder:

JSONObject jsonObject = new JSONObject(builder.toString());
JSONObject responseData = (JSONObject)jsonObject.get("responseData");
JSONArray results = (JSONArray)responseData.get("results");
for(int i = 0; i < results.length(); i++)
{
     JSONObject urlObject  = (JSONObject)results.get(i);
     System.out.println(urlObject.get("url"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM