Android将JSONArray转换为String Array

时间:2014-07-25 03:19:47

标签: java android arrays json

我从Json获取数据并且有一个Json数组。我想将该Json数组转换为String数组,因此我可以将其发送到另一个活动并在ListView中显示。

这是我的java代码

    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();
        }
   }

我尝试使用该代码转换JSONarray,但我意识到该代码用于将JSONArray转换为String

这是我的JSON数据

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

我想将item_list数组转换为像这样

item_list = {"Ascending", "Descending"}

所以我可以将它发送到另一个活动中使用Intent并在ListView

中显示它

2 个答案:

答案 0 :(得分:5)

你有什么

String item_list = itemList.toString();

您需要解析items_list的{​​{1}}。

JSONArray

现在您可以将字符串添加到列表/数组中,然后执行所需操作。

答案 1 :(得分:1)

请查看本教程。

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

也许这会对你有所帮助。

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();
    }
}
相关问题