как анализировать массив Json внутри массива Json в Android

Я хочу знать, как разобрать массив JSON внутри в другой массив JSON. Я новичок в разработке Android, пожалуйста, помогите мне и заранее спасибо. URL моей веб-службы здесь мой код: -

public class  ProductsAsynTask extends AsyncTask<String,Void,Boolean>{

    ProgressDialog dialog;

    protected void onPreExecute(){
        super.onPreExecute();
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("Loading, Please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);
    }

    protected Boolean doInBackground(String... param){
        try {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(param[0]);
            HttpResponse response = client.execute(post);

            int status = response.getStatusLine().getStatusCode();
            if(status == 200){
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONObject jsonObject = new JSONObject(data);
                JSONArray jArray = jsonObject.getJSONArray("product");

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

                    JSONObject jsonObject1 = jArray.getJSONObject(i);

                    Products products = new Products();

                    products.setId(jsonObject1.getString("id"));
                    products.setName(jsonObject1.getString("name"));
                    products.setManufacturer(jsonObject1.getString("manufacturer"));
                    products.setModel(jsonObject1.getString("model"));
                    products.setReward(jsonObject1.getString("reward"));
                    products.setPoints(jsonObject1.getString("points"));
                    products.setImage(jsonObject1.getString("image"));
                    products.setPrice(jsonObject1.getString("price"));
                    products.setSpecial(jsonObject1.getString("special"));

                    JSONArray jArray1 = jArray.getJSONArray(i);

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

                        JSONObject jsonObject2 = jArray1.getJSONObject(j);

                        products.setDiscounts_quantity(jsonObject2.getString("quantity"));
                        products.setDiscounts_price(jsonObject2.getString("price"));
                    }
                    JSONArray jArray2 = jArray.getJSONArray(i);

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

                        JSONObject jsonObject2 = jArray2.getJSONObject(j);

                        products.setOptions_product_option_id(jsonObject2.getString("product_option_id"));
                        products.setOptions_option_id(jsonObject2.getString("option_id"));
                        products.setOptions_name(jsonObject2.getString("name"));
                        products.setOptions_type(jsonObject2.getString("type"));

                        JSONArray jsonArray3 = jArray2.getJSONArray(j);

                        for(int k = 0;k < jsonArray3.length();k++){

                            JSONObject jsonObject3 = jsonArray3.getJSONObject(k);

                            products.setOptions_option_value_product_option_value_id(jsonObject3.getString("product_option_value_id"));
                            products.setOptions_option_value_option_value_id(jsonObject3.getString("option_value_id"));
                            products.setOptions_option_value_name(jsonObject3.getString("name"));
                            products.setOptions_option_value_image(jsonObject3.getString("image"));
                            products.setOptions_option_value_price(jsonObject3.getString("price"));
                            products.setOptions_option_value_price_prefix(jsonObject3.getString("price_prefix"));
                        }

                            products.setOptions_required(jsonObject2.getString("required"));
                    }

                            products.setMinimum(jsonObject1.getString("minimum"));
                            products.setRating(jsonObject1.getString("rating"));
                            products.setDescription(jsonObject1.getString("description"));

                            JSONArray jsonArray = jArray.getJSONArray(i);

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

                                JSONObject jsonObject2 = jsonArray.getJSONObject(j);

                                products.setAttribute_groups_attribute_group_id(jsonObject2.getString("attribute_group_id"));
                                products.setAttribute_groups_name(jsonObject2.getString("name"));

                                JSONArray jsonArray1 = jsonArray.getJSONArray(j);

                                for(int k = 0; k < jsonArray1.length();k++){

                                    JSONObject jsonObject3 = jsonArray1.getJSONObject(k);

                                    products.setAttribute_groups_attribute_attribute_id(jsonObject3.getString("attribute_id"));
                                    products.setAttribute_groups_attribute_name(jsonObject.getString("name"));
                                    products.setAttribute_groups_attribute_text(jsonObject3.getString("text"));
                                }
                            }
                    productsList.add(products);
                }
                return true;
            }
            else if(status == 500){
                Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
            }

        }catch (ClientProtocolException e){
            Log.e("Error :",e.getMessage());
        }catch (IOException e){
            Log.e("Error :",e.getMessage());
        }catch (JSONException e){
            Log.e("Error :",e.getMessage());
        }catch (Exception e){
            Log.e("Error :",e.getMessage());
        }
        return false;
    }

    protected void onPostExecute(Boolean result){

        dialog.cancel();
        adapter.notifyDataSetChanged();
        if(result == false){
            Toast.makeText(MainActivity.this,"Data is not Parsed",Toast.LENGTH_LONG).show();
        }
        else{
            ProductsAdapter adapter = new ProductsAdapter(getApplicationContext(),R.layout.content_main,productsList);
            listView.setAdapter(adapter);
        }
    }
}

Я новичок в разработке Android, пожалуйста, помогите мне и заранее спасибо.


person Anand Jain    schedule 19.09.2015    source источник
comment
опубликуйте свою структуру json   -  person Shadow    schedule 19.09.2015
comment
Я дал ссылку на свою json-структуру opencart.codeniques.com /myshop/?route=feed/web_api/   -  person Anand Jain    schedule 19.09.2015


Ответы (3)


Чтобы взять другой массив в объекте, который вы должны изменить

JSONArray jArray1 = jArray.getJSONArray(i);

to

JSONArray jArray1 = jsonObject1.getJSONArray("discounts");
person Salva Savall    schedule 19.09.2015

В вашем ответе json «продукт» не является массивом json, это объект json. Измените это в своем doInBackground().

    protected Boolean doInBackground(String... param){
    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(param[0]);
        HttpResponse response = client.execute(post);

        int status = response.getStatusLine().getStatusCode();
        if(status == 200){
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity);

            JSONObject jsonObject = new JSONObject(data);


                JSONObject jsonObject1 = jsonObject.getJSONObject("product");

                Products products = new Products();

                products.setId(jsonObject1.getString("id"));
                products.setName(jsonObject1.getString("name"));
                products.setManufacturer(jsonObject1.getString("manufacturer"));
                products.setModel(jsonObject1.getString("model"));
                products.setReward(jsonObject1.getString("reward"));
                products.setPoints(jsonObject1.getString("points"));
                products.setImage(jsonObject1.getString("image"));
                products.setPrice(jsonObject1.getString("price"));
                products.setSpecial(jsonObject1.getString("special"));



                JSONArray jArray1 = jsonObject1.getJSONArray("discounts");

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

                    JSONObject jsonObject2 = jArray1.getJSONObject(j);

                    products.setDiscounts_quantity(jsonObject2.getString("quantity"));
                    products.setDiscounts_price(jsonObject2.getString("price"));
                }
                JSONArray jArray2 = jsonObject1.getJSONArray("options");

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

                    JSONObject jsonObject2 = jArray2.getJSONObject(j);

                    products.setOptions_product_option_id(jsonObject2.getString("product_option_value_id"));
                    products.setOptions_option_id(jsonObject2.getString("option_id"));
                    products.setOptions_name(jsonObject2.getString("name"));
                    products.setOptions_type(jsonObject2.getString("type"));

                    JSONArray jsonArray3 = jsonObject2.getJSONArray("option_value");

                    for(int k = 0;k < jsonArray3.length();k++){

                        JSONObject jsonObject3 = jsonArray3.getJSONObject(k);

                        products.setOptions_option_value_product_option_value_id(jsonObject3.getString("product_option_value_id"));
                        products.setOptions_option_value_option_value_id(jsonObject3.getString("option_value_id"));
                        products.setOptions_option_value_name(jsonObject3.getString("name"));
                        products.setOptions_option_value_image(jsonObject3.getString("image"));
                        products.setOptions_option_value_price(jsonObject3.getString("price"));
                        products.setOptions_option_value_price_prefix(jsonObject3.getString("price_prefix"));
                    }

                        products.setOptions_required(jsonObject2.getString("required"));
                }

                        products.setMinimum(jsonObject1.getString("minimum"));
                        products.setRating(jsonObject1.getString("rating"));
                        products.setDescription(jsonObject1.getString("description"));

                        JSONArray jsonArray = jsonObject1.getJSONArray("attribute_groups");

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

                            JSONObject jsonObject2 = jsonArray.getJSONObject(j);

                            products.setAttribute_groups_attribute_group_id(jsonObject2.getString("attribute_group_id"));
                            products.setAttribute_groups_name(jsonObject2.getString("name"));

                            JSONArray jsonArray1 = jsonObject2.getJSONArray("attribute");

                            for(int k = 0; k < jsonArray1.length();k++){

                                JSONObject jsonObject3 = jsonArray1.getJSONObject(k);

                                products.setAttribute_groups_attribute_attribute_id(jsonObject3.getString("attribute_id"));
                                products.setAttribute_groups_attribute_name(jsonObject.getString("name"));
                                products.setAttribute_groups_attribute_text(jsonObject3.getString("text"));
                            }
                        }
                productsList.add(products);
            }
            return true;
        }
        else if(status == 500){
            Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
        }

    }catch (ClientProtocolException e){
        Log.e("Error :",e.getMessage());
    }catch (IOException e){
        Log.e("Error :",e.getMessage());
    }catch (JSONException e){
        Log.e("Error :",e.getMessage());
    }catch (Exception e){
        Log.e("Error :",e.getMessage());
    }
    return false;
}
person Ved    schedule 19.09.2015
comment
JSONObject jsonObject1 = jArray.getJSONObject(product); Этот jArray?? - person Anand Jain; 21.09.2015
comment
Это моя ошибка изменила jArray на jsonObject. Отредактированный ответ. - person Ved; 21.09.2015
comment
Когда я пробую ваш код, он выдает ошибку JSONObject не может быть преобразован в JSONArray. - person Anand Jain; 21.09.2015
comment
Давайте продолжим это обсуждение в чате. - person Anand Jain; 22.09.2015

Json просто разберет файл json в один объект json, а затем вы можете просто сослаться на него.

person Cameron White    schedule 19.09.2015
comment
я не понимаю, что вы пытаетесь сказать, пожалуйста, объясните на примере @Cameron White - person Anand Jain; 19.09.2015