嵌套的JSON对象长度

时间:2012-10-08 07:55:44

标签: android 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个嵌套的JSONObject和2个值,即city_id和city_name_eng。 当我使用objJSON.length()时,它给我的长度为6.但相反,我希望有4个嵌套的JSONObjects,我怎样才能在运行时获得它? (嵌套的jsonobjects是3还是4或任何数字)

如何区分嵌套的JSONObjects和键值?

1 个答案:

答案 0 :(得分:1)

如果网站是您自己的网站,那么我建议您重新编写代码,以便在适当的时候返回JSONArray

否则,jsonObj.keys()将返回Iterator,您可以使用它来迭代密钥并解析对象。