如何在android中访问json数组

时间:2013-09-12 02:39:18

标签: android arrays json

我想在我的project.i中使用一个json文件。在下面的结构中有一个Json文件,我成功访问json数组“business”,但现在我想访问business_cat和business_cat,cat 1和cat 2我怎样才能获得这些价值?

 {
   "business":[
     {
      "id":"13",
      "category":"Dinner",
      "subcategory":"",
      "name_eng":"dinner 1",
      "name_arab":"dinner 1",
      "mobile":"12345",
      "address":"not now",
      "logo":"1.gif",
      "contact":"Call",
      "open_time":" ",
      "close_time":" "
      }
   ],
   "business_cat":[
  [
     "cat 1",
     {
        "name":"dish 1",
        "id":"7",
        "name_arab":"dish1",
        "price":"200",
        "logo":"laptop.jpeg"
     },
     {
        "name":"dish 2",
        "id":"8",
        "name_arab":"dish 2",
        "price":"123789",
        "logo":"micky.jpg"
     },
     {
        "name":"qaz",
        "id":"10",
        "name_arab":"zaq",
        "price":"12",
        "logo":"watch.jpg"
     },
     {
        "name":"wsx",
        "id":"11",
        "name_arab":"xsw",
        "price":"12",
        "logo":"micky.jpg"
     },
     {
        "name":"zxc",
        "id":"12",
        "name_arab":"vcxz",
        "price":"34",
        "logo":"camera.jpg"
     }
  ],
  [
     "cat2",
     {
        "name":"d1",
        "id":"9",
        "name_arab":"d1",
        "price":"300",
        "logo":"watch.jpg"
     }
      ]
   ]
   }

2 个答案:

答案 0 :(得分:0)

JSON对象以{开头,以{结尾},而JSON数组以[以#结尾]开头。

整个字符串将是JSONObject,可以通过json.getJSONArray(ARRAYNAME)从中提取每个数组

JSONObject json = new JSONObject(jsonString);
JSONArray business = json.getJSONArray("business");


//business
System.out.println("*****business*****"+business.length());
for(int i=0;i<business.length();i++){

 JSONObject json_data_business = business.getJSONObject(i);
 Log.i("log","id"+json_data_business.getInt("id")+
  ", category"+json_data_business.getString("category")
 );

// business_cat 

JSONArray business_cat = json.getJSONArray("business_cat");

System.out.println("*****business_cat*****"+business_cat.length());
for(int i=0;i<business_cat.length();i++){

 JSONObject json_data_business_cat = business_cat.getJSONObject(i);
 Log.i("log","id"+json_data_business_cat.getInt("id")+
  ", name"+json_data_business_cat.getString("name")
 );

}

答案 1 :(得分:0)

        JSONObject obj = new JSONObject(content);
        if (obj != null) {
            Iterator<?> it = obj.keys();
            while (it.hasNext()) {
                String key = it.next().toString();
                JSONArray value = (JSONArray) obj.optString(key);
                ---then you parse the JSONArray
            }
        }