如何解析没有数组名称的JSON数据?

时间:2018-05-12 17:52:49

标签: java android json parsing

我是JSON解析的新手。这段代码有效。但是如果JSON阵列上没有“totalHits”和“hits”,我怎么能直接访问“likes”和“webformatURL”?

 private void parseJSON() {

    String url="https://pixabay.com/api/?key=8947271-cb39739eaa5835e1eaa2f53c6&q=yellow+flowers&image_type=photo&pretty=true";

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

                    for (int i =  0; i < jsonArray.length(); i++){
                        JSONObject hit = jsonArray.getJSONObject(i);

                        String imageUrl = hit.getString("webformatURL");
                        int likeCount = hit.getInt("likes");

                        mExampleList.add(new ExampleItem(imageUrl, likeCount));
                    }

                    mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
                    mRecyclerView.setAdapter(mExampleAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }
    );
}

1 个答案:

答案 0 :(得分:0)

您可以使用Google Gson库将您的json直接解析为ArrayList对象。

你可以这样做。

print (zscores)
   zsores_B  zsores_C  zsores_D
1     500.0     800.0     300.0
2     400.0     900.0     500.0
4     500.0     200.0     100.0
5     400.0     300.0       0.0

这是你的模特课。

        JsonArray itemArray = new JsonArray(response);
        Type listType = new TypeToken<List<Model>>() {
        }.getType();
        List<Model> yourList = new Gson().fromJson(itemArray, listType);
        for (Model model : yourList) {
            //  use this list
            System.out.println(model.toString());
        }

将Gson添加到您的项目中。只需在class Model { private int id; private String title; private long date_add; private String poster; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getDate_add() { return date_add; } public void setDate_add(long date_add) { this.date_add = date_add; } public String getPoster() { return poster; } public void setPoster(String poster) { this.poster = poster; } @Override public String toString() { return "Model{" + "id=" + id + ", title='" + title + '\'' + ", date_add=" + date_add + ", poster='" + poster + '\'' + '}'; } }

中添加此依赖项即可
build.gradle