使用数组Json获取有关数组的数据

时间:2017-12-06 09:48:45

标签: android json listview baseadapter

我需要从 arrays 响应中提取两个json 以下是我的回复。

{
"data": [
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            }
        ],
        "id": "14",
        "cat_id": "x",
        "category": "Casual shirts"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            }
        ],
        "id": "15",
        "cat_id": "x",
        "category": "Jackets"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            },
            {
                "id": "833",
                "cat_id": "154",
                "sub_category": "Pepe jeans"
            },
            {
                "id": "834",
                "cat_id": "154",
                "sub_category": "John players"
            }
        ],
        "id": "154",
        "cat_id": "x",
        "category": "Jeans"
    }
],
"status": 100
}

尝试获取数据时,将其放入列表适配器中,其中我想在一个文本框中显示类别,而在另一个文本框中使用逗号分隔显示子类别。 像这样:

Category : Jeans

Sub Category :John players,Pepe jeans,Pan America,Roadster,wildcraft

我尝试通过为category和子类别创建模型类来实现此功能。正确获取类别,但获取所有subcategories

2 个答案:

答案 0 :(得分:1)

以下是相同的代码:

 try{
        JSONObject jsonObject = new JSONObject(jsonString);

        ArrayList<String> categoryList = new ArrayList<>();

        HashMap<String,ArrayList<String>> allCategory = new HashMap<>();
        JSONArray dataArray  = jsonObject.getJSONArray("data");
        for(int i=0;i<dataArray.length();i++)
        {
            JSONObject internalObject = dataArray.getJSONObject(i);

            categoryList.add(internalObject.getString("category"));

            JSONArray jsonArray = internalObject.getJSONArray("sub_cat");

            ArrayList<String> subCategoryList = new ArrayList<>();
            for(int j=0;j<jsonArray.length();j++)
            {
                subCategoryList.add(jsonArray.getJSONObject(j).getString("sub_category"));
            }

            allCategory.put(categoryList.get(i),subCategoryList);
        }

        Log.d("Check",hashMap+" ");
    }
    catch (Exception exe)
    {
        exe.printStackTrace();
    }

您将获得所有类别的categoryList和包含Hashmap的allCategory。用于将类别与其sub_categories列表进行映射。

被修改

以下是调用列表的MainActivity.java类:

public class MainActivity extends Activity {

ExpandableListAdapter listAdapter;
ExpandableListView expListView;


HashMap<String,ArrayList<String>> allCategory;
private ArrayList<String> categoryList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String[] mStrings = new String[20];

    allCategory= new HashMap<>();


    // get the listview
    expListView = (ExpandableListView) findViewById(R.id.lvExp);

    String jsonString = "{\n" +
            "\"data\": [\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"14\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Casual shirts\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"835\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"Roadster\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"836\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"wildcraft\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"15\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Jackets\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"835\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"Roadster\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"836\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"wildcraft\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"833\",\n" +
            "                \"cat_id\": \"154\",\n" +
            "                \"sub_category\": \"Pepe jeans\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"834\",\n" +
            "                \"cat_id\": \"154\",\n" +
            "                \"sub_category\": \"John players\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"154\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Jeans\"\n" +
            "    }\n" +
            "],\n" +
            "\"status\": 100\n" +
            "}";

    // preparing list data
    prepareListData(jsonString);

    listAdapter = new ExpandableListAdapter(this, categoryList, allCategory);


    // setting list adapter
    expListView.setAdapter(listAdapter);


}


/*
 * Preparing the list data
 */
private void prepareListData(String jsonString) {
    try{
        JSONObject jsonObject = new JSONObject(jsonString);

       categoryList = new ArrayList<>();


        JSONArray dataArray  = jsonObject.getJSONArray("data");
        for(int i=0;i<dataArray.length();i++)
        {
            JSONObject internalObject = dataArray.getJSONObject(i);

            categoryList.add(internalObject.getString("category"));

            JSONArray jsonArray = internalObject.getJSONArray("sub_cat");

            ArrayList<String> subCategoryList = new ArrayList<>();
            for(int j=0;j<jsonArray.length();j++)
            {
                subCategoryList.add(jsonArray.getJSONObject(j).getString("sub_category"));
            }

            allCategory.put(categoryList.get(i),subCategoryList);
        }

        Log.d("Check",allCategory+" ");
    }
    catch (Exception exe)
    {
        exe.printStackTrace();
    }

}
}

这是Expandlist Adapter:

public class ExpandableListAdapter extends BaseExpandableListAdapter {


HashMap<String,ArrayList<String>> listDataEditText;

int expandedGroup=0;

private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, ArrayList<String>> _listDataChild;






public ExpandableListAdapter(Context context, List<String> listDataHeader,
                             HashMap<String, ArrayList<String>> listChildData) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;

    listDataEditText  = new HashMap<>();

    for(int j=0;j<listDataHeader.size();j++) {
        ArrayList<String> preInsertion = new ArrayList<>();
        for (int i =0;i<this._listDataChild.get(_listDataHeader.get(j)).size();i++)
        {
                preInsertion.add("");
        }

        listDataEditText.put(listDataHeader.get(j),preInsertion);

    }

}


@Override
public Object getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}




@Override
public View getChildView(final int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {




    final String childText = (String) getChild(groupPosition, childPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_item, null);
    }
    TextView txtListChild = convertView.findViewById(R.id.lblListItem);






    txtListChild.setText(childText);
    return convertView;
}





@Override
public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this._listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this._listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(final int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    TextView lblListHeader = (TextView) convertView
            .findViewById(R.id.lblListHeader);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);




    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}



 }

以下是列表项目:

for GroupView“list_group”:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="81dp">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/lblListHeader"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="48dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="33dp" />


</RelativeLayout>
</android.support.constraint.ConstraintLayout>

for Child View“list_item”:

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/linearLayout4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.194"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.137">

    <TextView
        android:id="@+id/lblListItem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="17dp" />

</LinearLayout>


</android.support.constraint.ConstraintLayout>

尝试一下,如果需要更多,请告诉我。

编辑最新

使用此SimpleAdapter显示所有sub_categories列表:

public class SimpleAdapter extends BaseAdapter {


ArrayList<String> stringArrayList;
Context context;

public SimpleAdapter(Context context,ArrayList<String> stringArrayList)
{
    this.context = context;
    this.stringArrayList = stringArrayList;
}

@Override
public int getCount() {
    return stringArrayList.size();
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    if (view == null) {
        LayoutInflater infalInflater = (LayoutInflater) this.context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = infalInflater.inflate(R.layout.list_item, null);
    }
    TextView txtListChild = view.findViewById(R.id.lblListItem);






    txtListChild.setText(stringArrayList.get(i));

    return view;
}
}

并将主要布局设为:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp"
>



<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</ListView>

</LinearLayout> 

答案 1 :(得分:0)

JsonObject root = new JsonObject(your json);
JsonArray data =  root.getJsonArray("data");
for loop data.size
inside loop 
JsonObject jObj = data.getJsonObject(i);
JsonArray sub_cat = jObj.getJsonArray("sub_cat");
 for loop int j=0 to sub_cat.length
inside loop 
JsonObject obj= sub_cat .getJsonObject(i);
String sub_category = obj.getString("sub_category");// here you will get all sub_category data