Matthew
Matthew

Reputation: 95

Android convert JSONArray to String Array

I get data from Json and there's a Json array. I want to convert that Json array into String array, so I can send it into another activity and show it in ListView.

Here's My java code

    if (jsonStr != null) {
        try {

            foodsFilter = new JSONArray(jsonStr);

            // looping through All Contacts
            for (int i = 0; i < foodsFilter.length(); i++) {

                JSONObject c = foodsFilter.getJSONObject(i);
                if(c.getString("category_name").equals("Food")) {
                String category_name = c.getString(TAG_CATEGORY_NAME);
                String filter_type = c.getString(TAG_FILTER_TYPE);
                //String item_list = c.getString(TAG_ITEM_LIST);
                JSONArray itemList = new JSONArray(c.getString("item_list"));
                String item_list = itemList.toString();

                // tmp hashmap for single contact
                HashMap<String, String> filter = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                filter.put(TAG_CATEGORY_NAME, category_name);
                filter.put(TAG_FILTER_TYPE, filter_type);
                filter.put(TAG_ITEM_LIST, item_list);

                // adding contact to contact list
                foodsFilterList.add(filter);

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

I try that code to convert the JSONarray, but I realized that code is for convert the JSONArray into String.

Here's my JSON data

[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}]

I want to convert the item_list Array into like this

item_list = {"Ascending", "Descending"}

So I can send it into another activity use Intent and show it in ListView

Upvotes: 1

Views: 6445

Answers (2)

Raghunandan
Raghunandan

Reputation: 133560

What you have

String item_list = itemList.toString();

You need to parse items_list which is a JSONArray.

JSONArray itemList = new JSONArray(c.getString("item_list"));
// loop through the array itemList and get the items
for(int i=0;i<itemList.length();i++) 
{ 
String item = itemList.getString(i); // item at index i
}

Now you can add the strings to a list/array and then do what is required.

Upvotes: 5

Isuru
Isuru

Reputation: 161

Please have a look on this tutorial.

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

Maybe this would help you.

ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
    try {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        stringArray.add(jsonObject.toString());
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
}

Upvotes: 1

Related Questions