提问者:小点点

如何在Java的数组中获取数组中的json数据?


我想用Wordpress rest API在android studio中获取数据。 但我无法获得序列中数组的数据。 我尝试了for循环,但它没有工作。 下图中带下划线的序列是类别名称,是可变的。 我想获得这个系列下的名称name:data,但是我失败了。 如果你帮助我,我会很高兴的。

final String GET_URL = Server.WORDPRESS_REST_API_URL + Server.SERVER_URL + Get.SERVER_JSON_RECENTLY_POSTS;

        Log.d("serverurl", GET_URL);


        StringRequest request = new StringRequest(Request.Method.GET, GET_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {


                if (!response.equals(null)) {

                    Log.d("Your Array Response", response);

                    try {

                        JSONObject jsonObj = new JSONObject(response);
                        JSONArray jsonArray = jsonObj.getJSONArray(Get.SERVER_JSON_RECENTLY_POSTS_ARRAY);

                        for (int j = 0; j < jsonArray.length(); j++) {

                            Log.d("jsonarrays", String.valueOf(jsonArray) + j);


                            JSONObject jsonObject = jsonArray.getJSONObject(j);
                            JSONObject jsonObjects = jsonObject.getJSONObject("categories");
                            JSONObject jsonObjects2 = jsonObjects.getJSONObject("name");

                             Log.d("jsonobjects", String.valueOf(jsonObjects2));
}

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.d("Your error",e.getMessage());
                    }
                }

                else {
                    Log.d("Your Array Response", "Data Null");
                }

共1个答案

匿名用户

首先,我建议您根据它们在JSON中的含义来命名变量,这将使您(和我们)更容易进行可视化。

您的类别似乎也是一个数组,在for循环中,您并没有遍历它。 保存类别的变量应该是JSONArray,数组的位置0将是您试图获取的JSONObject。

如果我正确理解了您的代码,JSONObjects应该是我所说的数组,遍历它并尝试从里面的JSONObjects获取您想要的属性。