没有名称的解析json数组

问题描述 投票:0回答:2

我正在尝试解析JSON数组并将其添加到我的适配器类。

我的代码:

String url = "https://api.github.com/users";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                JSONArray results = response.getJSONArray();   //  error in this line since there is no array name


                for(int i = 0;i < results.length();i++){
                    JSONObject result = results.getJSONObject(i);
                    String name = result.getString("login");
                    users.add(new User(name.substring(0,1).toUpperCase() + name.substring(1),result.getString("avatar_url")));
                }
//              notify that data has changed in recyclerview
                notifyDataSetChanged();

            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("cs50", "Json error", e);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("cs50","Github User List error",error);
        }
    });

[您可以看到我正在尝试从Github API URL获得响应,但是由于没有数组名,但是我的代码需要一个参数,因此我收到了错误消息。我该如何解析?

java android arrays android-volley response
2个回答
1
投票

更改此行

StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://api.github.com/users", response -> {

        Log.d(TAG, "_ApiGetGithubUsers: " + response);

        if (response != null && !response.isEmpty()) {
            try {
                JSONArray usersArray = new JSONArray(response);

                for (int i = 0; i < usersArray.length(); i++) {

                    JSONObject user = usersArray.getJSONObject(i);
                    Log.d(TAG, "_ApiGetGithubUsers: "+user.getString("login"));
                }


            } catch (Exception e) {
                Log.d(TAG, "_ApiGetGithubUsers: " + e);
                Toast.makeText(context, R.string.someErrorOccurred, Toast.LENGTH_SHORT).show();
            }
        } else
            Toast.makeText(context, R.string.someErrorOccurred, Toast.LENGTH_SHORT).show();


    }, error -> {

    });

    AppController.getInstance().addToRequestQueue(stringRequest);

这是我使用的方法,它正在工作并且正在分析附加日志图像以供参考。Logs


0
投票

我认为您可以使用改造库,将依赖项添加到应用gradle中。

implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:retrofit:2.5'

创建用户类别以获取响应。

public class User {

    @SerializedName("login")
    @Expose
    private String login;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("node_id")
    @Expose
    private String nodeId;
    @SerializedName("avatar_url")
    @Expose
    private String avatarUrl;
    @SerializedName("gravatar_id")
    @Expose
    private String gravatarId;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("html_url")
    @Expose
    private String htmlUrl;
    @SerializedName("followers_url")
    @Expose
    private String followersUrl;
    @SerializedName("following_url")
    @Expose
    private String followingUrl;
    @SerializedName("gists_url")
    @Expose
    private String gistsUrl;
    @SerializedName("starred_url")
    @Expose
    private String starredUrl;
    @SerializedName("subscriptions_url")
    @Expose
    private String subscriptionsUrl;
    @SerializedName("organizations_url")
    @Expose
    private String organizationsUrl;
    @SerializedName("repos_url")
    @Expose
    private String reposUrl;
    @SerializedName("events_url")
    @Expose
    private String eventsUrl;
    @SerializedName("received_events_url")
    @Expose
    private String receivedEventsUrl;
    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("site_admin")
    @Expose
    private Boolean siteAdmin;

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNodeId() {
        return nodeId;
    }

    public void setNodeId(String nodeId) {
        this.nodeId = nodeId;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

    public String getGravatarId() {
        return gravatarId;
    }

    public void setGravatarId(String gravatarId) {
        this.gravatarId = gravatarId;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getHtmlUrl() {
        return htmlUrl;
    }

    public void setHtmlUrl(String htmlUrl) {
        this.htmlUrl = htmlUrl;
    }

    public String getFollowersUrl() {
        return followersUrl;
    }

    public void setFollowersUrl(String followersUrl) {
        this.followersUrl = followersUrl;
    }

    public String getFollowingUrl() {
        return followingUrl;
    }

    public void setFollowingUrl(String followingUrl) {
        this.followingUrl = followingUrl;
    }

    public String getGistsUrl() {
        return gistsUrl;
    }

    public void setGistsUrl(String gistsUrl) {
        this.gistsUrl = gistsUrl;
    }

    public String getStarredUrl() {
        return starredUrl;
    }

    public void setStarredUrl(String starredUrl) {
        this.starredUrl = starredUrl;
    }

    public String getSubscriptionsUrl() {
        return subscriptionsUrl;
    }

    public void setSubscriptionsUrl(String subscriptionsUrl) {
        this.subscriptionsUrl = subscriptionsUrl;
    }

    public String getOrganizationsUrl() {
        return organizationsUrl;
    }

    public void setOrganizationsUrl(String organizationsUrl) {
        this.organizationsUrl = organizationsUrl;
    }

    public String getReposUrl() {
        return reposUrl;
    }

    public void setReposUrl(String reposUrl) {
        this.reposUrl = reposUrl;
    }

    public String getEventsUrl() {
        return eventsUrl;
    }

    public void setEventsUrl(String eventsUrl) {
        this.eventsUrl = eventsUrl;
    }

    public String getReceivedEventsUrl() {
        return receivedEventsUrl;
    }

    public void setReceivedEventsUrl(String receivedEventsUrl) {
        this.receivedEventsUrl = receivedEventsUrl;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Boolean getSiteAdmin() {
        return siteAdmin;
    }

    public void setSiteAdmin(Boolean siteAdmin) {
        this.siteAdmin = siteAdmin;
    }

    @Override
    public String toString() {
        return "User{" +
                "login='" + login + '\'' +
                ", id=" + id +
                ", nodeId='" + nodeId + '\'' +
                ", avatarUrl='" + avatarUrl + '\'' +
                ", gravatarId='" + gravatarId + '\'' +
                ", url='" + url + '\'' +
                ", htmlUrl='" + htmlUrl + '\'' +
                ", followersUrl='" + followersUrl + '\'' +
                ", followingUrl='" + followingUrl + '\'' +
                ", gistsUrl='" + gistsUrl + '\'' +
                ", starredUrl='" + starredUrl + '\'' +
                ", subscriptionsUrl='" + subscriptionsUrl + '\'' +
                ", organizationsUrl='" + organizationsUrl + '\'' +
                ", reposUrl='" + reposUrl + '\'' +
                ", eventsUrl='" + eventsUrl + '\'' +
                ", receivedEventsUrl='" + receivedEventsUrl + '\'' +
                ", type='" + type + '\'' +
                ", siteAdmin=" + siteAdmin +
                '}';
    }
}

为端点URL创建API接口。

public interface APIInterface {

    @GET("/users")
    Call<List<User>> getGitHubUser();
}

创建翻新API客户端。

public class APIClient {


    /**
     * Get Retrofit Instance
     */
    private static Retrofit getRetrofitInstance() {

        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        return new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }


    public static APIInterface getApiInterface() {
        return getRetrofitInstance().create(APIInterface.class);
    }
} 

然后调用以下方法以获取您的解析数据。

public void getUserList() {
    APIInterface apiInterface=APIClient.getApiInterface();
    Call<List<User>> call= apiInterface.getGitHubUser();
    call.enqueue(new Callback<List<User>>() {
        @Override
        public void onResponse(Call<List<User>> call, Response<List<User>> response) {
            List<User> userList= response.body();
            System.out.println(userList);
        }

        @Override
        public void onFailure(Call<List<User>> call, Throwable t) {

        }
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.