首页 > 解决方案 > 我无法从 JSON 数组中获取对象

问题描述

这是 JSON 网址

我想在actor中获取所有对象,我该怎么做?

private void parseJSON() {
    String url = "https://api.github.com/events";

    final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                   try{
                       JSONArray jsonArray = response.getJSONArray("actor");

                       for(int i =0; i <jsonArray.length();i ++){
                           JSONObject act = jsonArray.getJSONObject(i);
                           int id = act.getInt("id");
                           String imageUrl = act.getString("avatar_url");
                           String login = act.getString("login");
                           String displaylogin = act.getString("display_login");
                           String gravatar_id = act.getString("gravatar_id");
                           String url = act.getString("url");  

标签: javaandroidjson

解决方案


actor不是数组。

你可以读到actor类似的东西

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JacksonExample2 {

    private static final String jsonStr = "YOUR JSON";

    public static void main(String[] args) throws JSONException {
        JSONArray jsonArray = new JSONArray(jsonStr);
        for(int i=0;i<jsonArray.length();i++) {
            JSONObject item = (JSONObject) jsonArray.get(i);
            JSONObject actor = (JSONObject) item.get("actor");
            // You can read all properties of actor like 'actor.getString("avatar_url");'
            System.out.println(actor);
        }
    }

}


推荐阅读