尝试访问google api时Java中的JSON错误

时间:2013-11-11 10:03:05

标签: java json google-api

以下是测试代码,其中我试图通过google api发布一些查询,api应该在json parseable字符串中发送响应。 当我打印字符串时,我清楚地看到了诸如url之类的实体,但是当我尝试从JSON Object获取这些实体时,我得到了错误。

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)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

检查json字符串后:

你不能直接获取“url”,一旦你将流读入StringBuilder就得到你需要做的“url”:

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"));
}