1

我有以下网址:

events_value = new URL("https://graph.facebook.com/me/events?access_token="+access_token);

URL 给了我以下响应:

https://graph.facebook.com/me/events?access_token=AAAAAAITEghMBAIBxLGB3PBYH3U5eF1reKAhNQQy85HWNuqGOl9NG2hsCCF8xLgMyc4bG51uo5dgt5c3M3UNcPnqhPVCtVZC4WVLveRmYRakas9AtQ

我试图将其放入 JSONArray:

JSONArray jArray = new JSONArray(events_value);   //this where the problem comes     
final String[] array_spinner = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
    JSONObject json_data = jArray.getJSONObject(i);
    String jj=json_data.getString("name");
    array_spinner[i] = jj;         
}

创建数组时无法输入 events_value。

请帮忙!

4

3 回答 3

1

此代码可能会对您有所帮助。尝试这个。

        JSONArray jArray = null;

        try {
        JSONObject json;
        // getting JSON string from URL
        if (url != null) {
            json = jParser.getJSONFromUrl(url);
            System.out.println("reading from url" + json);
        }

        // Getting Array of jArray
        jArray = json.getJSONArray(TAG_NAME);

        // looping through All jArray
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject c = jArray.getJSONObject(i);
            Log.d(TAG_TYPE, c.getString(TAG_NAME));//print in log cat

        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
于 2012-12-04T07:20:38.393 回答
1
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

....

然后你的代码:

JSONArray jArray = (JSONArray) readJsonFromUrl(events_value);
final String[] array_spinner = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
    JSONObject json_data = jArray.getJSONObject(i);
    String jj=json_data.getString("name");
    array_spinner[i] = jj;         
}
于 2012-12-04T07:40:27.867 回答
0

也许您的问题中有错字,但 events_value 是 URL 字符串而不是 JSONArray,因此您肯定会遇到异常。由于相关 url 的令牌已过期,我无法看到确切的响应,但请尝试检查响应是 JSONObject 还是 JSONArray。一个 JSONArray 必须在开头和结尾都有 '[' 和 ']',如果不是,它就是一个 JSONObject。

更新

响应字符串具有数据和分页字段。所以数据字段是一个 JSONArray 和分页 JSONObject。要检索数据,请使用以下内容:

JSONObject response = new JSONObject(responseString)
JSONArray data = response.getJSONArray("data");

然后为数据数组上的每个项目解析属性。

于 2012-12-04T07:17:08.330 回答