Android convert JSONObject to HashMap and display in ListView with SimpleAdapter

前端 未结 2 1043
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 04:05

I try to search converting JSONObject to HashMap but most of the results are for Java not Android. Hence, I hope someone can share if you have experien

相关标签:
2条回答
  • 2021-01-24 04:38

    try this code to convert Jsonobject to hashmap

     Map<String, String> params = new HashMap<String, String>();
                    try
                    {
    
                       Iterator<?> keys = jsonObject.keys();
    
                        while (keys.hasNext())
                        {
                            String key = (String) keys.next();
                            String value = jsonObject.getString(key);
                            params.put(key, value);
    
                        }
    
    
                    }
                    catch (Exception xx)
                    {
                        xx.toString();
                    }
    
    0 讨论(0)
  • 2021-01-24 04:46

    You could do something like this:

    ListView listView = (ListView) findViewById(R.id.listView);
    
    // ...
    
    @Override
    public void onResponse(JSONObject response) {
        List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    
        try {
            Iterator<String> iterator = response.keys();
    
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = response.getString(key);
    
                HashMap<String, String> map = new HashMap<>();
                map.put(KEY_ID, key);
                map.put(KEY_NAME, value);
    
                list.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        if(list.size() > 0) {
            String[] from = {KEY_ID, KEY_NAME};
            int[] to = {R.id.text_id, R.id.text_name};
    
            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list,
                R.layout.list_item, from, to);
    
            listView.setAdapter(adapter);
        }
    }
    
    0 讨论(0)
提交回复
热议问题