简体   繁体   English

如何解析来自Android中Web服务的主数组中具有相同名称的json子数组?

[英]How to parse json sub arrays having the same names inside the main array coming from a web service in android?

I want to populate spinners from json data coming from a web service. 我想用来自Web服务的json数据填充微调框。 I have a main array named as "categoriesList" which includes sub-arrays named as "subcategories" but these arrays have the same names and contain objects of data. 我有一个名为“ categoriesList”的主数组,其中包含名为“ subcategories”的子数组,但是这些数组具有相同的名称并包含数据对象。 I want to populate the 2nd spinner of subcategories based on the selection of 1st spinner ie categoriesList. 我想基于对第一个微调器的选择,即categoryList,来填充第二个子类别的微调器。 The problem is that when I select an item from 1st spinner(categoriesList) then the 2nd spinner displays all the sub arrays but i need only the respective subarray to display in 2nd spinner(subcategories). 问题是,当我从第一个Spinner(categoriesList)中选择一个项目时,第二个Spinner将显示所有子数组,但是我只需要相应的子数组即可在第二个Spinner(subcategories)中显示。

Following is the json data format: 以下是json数据格式:

{
"success": true,
"code": 200,
"message": "Data  Found.",
"content": {
    "companyTypes": [
        {
            "id": 1,
            "title": "Distributor"
        },
        {
            "id": 2,
            "title": "Mechanics"
        },
        {
            "id": 3,
            "title": "Retailer"
        },
        {
            "id": 4,
            "title": "Others"
        }
    ],
    "citiesList": [
        {
            "id": 1,
            "name": "Sharja"
        }
    ],
    "brandsList": [
        {
            "id": 1,
            "title": "Test Brand"
        },
        {
            "id": 2,
            "title": "Brand 2"
        },
        {
            "id": 3,
            "title": "Brand 3"
        },
        {
            "id": 4,
            "title": "Brand 4"
        },
        {
            "id": 5,
            "title": "Brand 5"
        }
    ],
    "categoriesList": [
        {
            "id": 1,
            "title": "Test Category",
            "subCategories": [
                {
                    "id": 1,
                    "title": "sub category 1"
                },
                {
                    "id": 5,
                    "title": "Sub Category 5"
                }
            ]
        },
        {
            "id": 2,
            "title": "Category 2",
            "subCategories": [
                {
                    "id": 2,
                    "title": "Sub Category 2"
                },
                {
                    "id": 3,
                    "title": "Sub Category 3"
                }
            ]
        },
        {
            "id": 3,
            "title": "Category 3",
            "subCategories": [
                {
                    "id": 4,
                    "title": "Sub Category 4"
                }
            ]
        }
    ]
}
}

And this my android java code: 这是我的android java代码:

categoryList code 类别列表代码

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

                    try {
                        final ArrayList<HashMap<String, String>> myArrList = new ArrayList<HashMap<String, String>>();
                        HashMap<String, String> map;

                        jsonObjectResponse = new JSONObject(response);
                        jsonObjectContent = jsonObjectResponse.getJSONObject("content");

                        jsonArrayCompanyTypes = jsonObjectContent.getJSONArray("categoriesList");

                        for (int i = 0; i < jsonArrayCompanyTypes.length(); i++) {
                            jsonObjectID = jsonArrayCompanyTypes.getJSONObject(i);

                            distributorId = jsonObjectID.getInt("id");

                            title = jsonObjectID.getString("title");

                            map = new HashMap<String, String>();
                            map.put("title", title);
                            map.put("id", distributorId + "");
                            myArrList.add(map);

                            //Log.i("Rsp", "onResponse: " + distributorId + "------Title: " + title);
                        }

                        SimpleAdapter simpleAdapter;
                        simpleAdapter = new SimpleAdapter(getActivity(), myArrList, R.layout.activity_show,
                                new String[]{"title"},
                                new int[]{R.id.tv_column_name});
                        spinnercategoriesList.setAdapter(simpleAdapter);

                        spinnercategoriesList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                selectedCompanyType = myArrList.get(position).get("title").toString();

                                categoryId = (int) (spinnercategoriesList.getSelectedItemId() + 1);

                                //populateCompanies(DIST_ID);

                                //TODO populate the subcategories spinner
                                populateSpinnerSubCategories(categoryId);

                                loadCategories();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    Volley.newRequestQueue(getActivity()).add(request);
}

SubCategory code 子类别代码

public void populateSpinnerSubCategories(final int categoryId) {

    String url = "http://radial-energy.com/radial/api/configurations";

    StringRequest request = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        final ArrayList<HashMap<String, String>> myArrList = new ArrayList<HashMap<String, String>>();
                        HashMap<String, String> map;

                        String subCategory = null;
                        int subCatId = 0;

                        jsonObjectResponse = new JSONObject(response);
                        jsonObjectContent = jsonObjectResponse.getJSONObject("content");

                        JSONArray jsonArrayCategories = jsonObjectContent.getJSONArray("categoriesList");

                        for (int i = 0; i < jsonArrayCategories.length(); i++) {
                            jsonObjectID = jsonArrayCategories.getJSONObject(i);

                            JSONArray jsonArraySubCategories = new
                                    JSONArray(jsonArrayCategories.getJSONObject(i)
                                    .getString("subCategories"));

                            System.out.println("Sub Categories Array: " + jsonArraySubCategories);

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

                                JSONObject jsonObjectSubCategories = jsonArraySubCategories.getJSONObject(j);

                                subCatId = jsonObjectSubCategories.getInt("id");

                                subCategory = jsonObjectSubCategories.getString("title");

                                Log.d("CATEGORY: ", subCategory);

                                map = new HashMap<String, String>();
                                map.put("title", subCategory);
                                map.put("id", subCatId + "");
                                myArrList.add(map);
                            }
                        }

                        SimpleAdapter simpleAdapter;
                        simpleAdapter = new SimpleAdapter(getActivity(), myArrList,
                                R.layout.activity_show, new String[]{"title"},
                                new int[]{R.id.tv_column_name});

                        spinnerSubcategoriesList.setAdapter(simpleAdapter);

                        spinnerSubcategoriesList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                String selectedSubCategory = myArrList.get(position).get("title").toString();

                                //DIST_ID = (int) (spinnerSubcategoriesList.getSelectedItemId() + 1);

                                //populateCompanies(DIST_ID);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },

            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity(), error.getMessage().toString(), Toast.LENGTH_SHORT).show();
                }
            });

    Volley.newRequestQueue(getActivity()).add(request);
}

Describe data model 描述数据模型

class DataItem {
     String id;
     String title;
     List<DataItem> subCategories;
}

class DataContent {
     List<DataItem> companyTypes;
     List<DataItem> citiesList;
     List<DataItem> brandsList;
     List<DataItem> categoriesList;
}

class DataResponse {
     Boolean success;
     Integer code;
     String message;
     DataContent content;  
}

And just use Gson to parse your response 并使用Gson解析您的回复

@Override
public void onResponse(String response) {
     Gson gson = new GsonBuilder().create();
     DataResponse dataResponse = gson.fromJson(response, DataResponse.class);
     ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM