2012-10-08 262 views
1

我有以下的JSON字符串。嵌套的JSON對象長度

{ 
    "data": [ 
    { 
     "city_id": "1", 
     "city_name_eng": "Multan", 
     "0": { 
     "category_id": "1", 
     "city_id": "1", 
     "category_name_eng": "Mango", 
     "0": { 
      "product_id": "1", 
      "category_id": "1", 
      "product_name_eng": "Mango1" 
     }, 
     "1": { 
      "product_id": "2", 
      "category_id": "1", 
      "product_name_eng": "Mango2" 
     }, 
     "2": { 
      "product_id": "3", 
      "category_id": "1", 
      "product_name_eng": "Mango3" 
     }, 
     "3": { 
      "product_id": "4", 
      "category_id": "1", 
      "product_name_eng": "Mango1" 
     } 
     }, 
     "1": { 
     "category_id": "2", 
     "city_id": "1", 
     "category_name_eng": "Shoes" 
     }, 
     "2": { 
     "category_id": "3", 
     "city_id": "1", 
     "category_name_eng": "Bank" 
     } 
    }, 
    { 
     "city_id": "2", 
     "city_name_eng": "Lahore", 
     "3": { 
     "category_id": "4", 
     "city_id": "2", 
     "category_name_eng": "Food" 
     }, 
     "4": { 
     "category_id": "5", 
     "city_id": "2", 
     "category_name_eng": "Computer" 
     }, 
     "5": { 
     "category_id": "6", 
     "city_id": "2", 
     "category_name_eng": "Mobile" 
     } 
    } 
    ] 
} 

我想擁有JSONObject的長度。基本上,具有"city_id": "1"的第一個對象具有4個嵌套的JSONObjects和2個值,即city_id和city_name_eng。 當我使用objJSON.length()時,它給了我6的長度。但相反,我想擁有4個嵌套JSONObjects,我如何在運行時獲得它? (無論嵌套的jsonobjects是3或4或任何數字)

如何區分嵌套的JSONObjects和鍵值?

+1

爲什麼不能使用JSONArray而不是將JSONObjects命名爲0,1,2等?這將使它更方便處理.. –

+0

如何做到這一點?我有一個來自PHP網站的JSON響應。 在那裏我用'json_encode(array('data'=> $ data));'' – Zeeshan

回答

1

如果網站是您自己的網站,那麼我建議重新編寫代碼以在適當的情況下返回JSONArray

否則,jsonObj.keys()將返回Iterator,您可以使用它來遍歷鍵並解析出您的對象。