将JSON数据解析为listView

时间:2011-08-23 01:15:01

标签: java android arrays json listview

  1. 如何将我的JSON数据导入listview?我要做的就是遍历JSON数据并抓住前两个元素并将它们添加到我的listview中的两个文本字段中。
  2. 但是当我执行下面的代码时,它只是将整个数组元素放入列表视图括号和全部。它增加但只是主数组而不是子项。 (如果这是有道理的)?

    下面是我的json数据,在“ //循环数组”之后神奇地发生了:

    [["Ace Tattooing Co","80260","(303) 427-3522 ","461 W 84th Ave",""],["Think Tank Tattoo","80209","(720) 932-0124","172 S Broadway",""]]
    

    到目前为止,这是我的脚本:

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class ShowShop extends ListActivity {
    
        private static final String TAG = "MyApp";  
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.ziplist_layout);
    
             Bundle bundle = getIntent().getExtras();
             String shop_data = bundle.getString("shopData");
             Log.v(TAG, shop_data);
    
             ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    
            //Get the data (see above)
                   try{
                //Get the element that holds the earthquakes ( JSONArray )
                       JSONArray jsonShopArray = new JSONArray(shop_data);
    
    
                            **//Loop the Array**
                    for(int i=0;i < jsonArray.length();i++){                        
    
    HashMap<String, String> map = new HashMap<String, String>();
                    JSONArray e = jsonShopArray.getJSONArray(i);
    
                    Log.v(TAG, e.toString(i));
                    map.put("id",  String.valueOf(1));
                    map.put("name", "Store name:" + e.toString(2));
                    map.put("zipcode", "Zipcode: " +  e.toString(3));
                    mylist.add(map);
            }
                   }catch(JSONException e)        {
                     Log.e("log_tag", "Error parsing data "+e.toString());
                   }
    
                   ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.shop_list,
                           new String[] { "name", "zipcode" },
                           new int[] { R.id.item_title, R.id.item_subtitle });
    
           setListAdapter(adapter);
    
    
    
    
            /**Toast.makeText(ShowShop.this, zipReturn, Toast.LENGTH_LONG).show(); */
    
        }
    }
    

1 个答案:

答案 0 :(得分:3)

e.toString不正确http://developer.android.com/reference/org/json/JSONArray.html#toString(int

您应该使用getStringgetInt或getWhatever